es6.js 4.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977939789397993980939819398293983939849398593986939879398893989939909399193992939939399493995939969399793998939999400094001940029400394004940059400694007940089400994010940119401294013940149401594016940179401894019940209402194022940239402494025940269402794028940299403094031940329403394034940359403694037940389403994040940419404294043940449404594046940479404894049940509405194052940539405494055940569405794058940599406094061940629406394064940659406694067940689406994070940719407294073940749407594076940779407894079940809408194082940839408494085940869408794088940899409094091940929409394094940959409694097940989409994100941019410294103941049410594106941079410894109941109411194112941139411494115941169411794118941199412094121941229412394124941259412694127941289412994130941319413294133941349413594136941379413894139941409414194142941439414494145941469414794148941499415094151941529415394154941559415694157941589415994160941619416294163941649416594166941679416894169941709417194172941739417494175941769417794178941799418094181941829418394184941859418694187941889418994190941919419294193941949419594196941979419894199942009420194202942039420494205942069420794208942099421094211942129421394214942159421694217942189421994220942219422294223942249422594226942279422894229942309423194232942339423494235942369423794238942399424094241942429424394244942459424694247942489424994250942519425294253942549425594256942579425894259942609426194262942639426494265942669426794268942699427094271942729427394274942759427694277942789427994280942819428294283942849428594286942879428894289942909429194292942939429494295942969429794298942999430094301943029430394304943059430694307943089430994310943119431294313943149431594316943179431894319943209432194322943239432494325943269432794328943299433094331943329433394334943359433694337943389433994340943419434294343943449434594346943479434894349943509435194352943539435494355943569435794358943599436094361943629436394364943659436694367943689436994370943719437294373943749437594376943779437894379943809438194382943839438494385943869438794388943899439094391943929439394394943959439694397943989439994400944019440294403944049440594406944079440894409944109441194412944139441494415944169441794418944199442094421944229442394424944259442694427944289442994430944319443294433944349443594436944379443894439944409444194442944439444494445944469444794448944499445094451944529445394454944559445694457944589445994460944619446294463944649446594466944679446894469944709447194472944739447494475944769447794478944799448094481944829448394484944859448694487944889448994490944919449294493944949449594496944979449894499945009450194502945039450494505945069450794508945099451094511945129451394514945159451694517945189451994520945219452294523945249452594526945279452894529945309453194532945339453494535945369453794538945399454094541945429454394544945459454694547945489454994550945519455294553945549455594556945579455894559945609456194562945639456494565945669456794568945699457094571945729457394574945759457694577945789457994580945819458294583945849458594586945879458894589945909459194592945939459494595945969459794598945999460094601946029460394604946059460694607946089460994610946119461294613946149461594616946179461894619946209462194622946239462494625946269462794628946299463094631946329463394634946359463694637946389463994640946419464294643946449464594646946479464894649946509465194652946539465494655946569465794658946599466094661946629466394664946659466694667946689466994670946719467294673946749467594676946779467894679946809468194682946839468494685946869468794688946899469094691946929469394694946959469694697946989469994700947019470294703947049470594706947079470894709947109471194712947139471494715947169471794718947199472094721947229472394724947259472694727947289472994730947319473294733947349473594736947379473894739947409474194742947439474494745947469474794748947499475094751947529475394754947559475694757947589475994760947619476294763947649476594766947679476894769947709477194772947739477494775947769477794778947799478094781947829478394784947859478694787947889478994790947919479294793947949479594796947979479894799948009480194802948039480494805948069480794808948099481094811948129481394814948159481694817948189481994820948219482294823948249482594826948279482894829948309483194832948339483494835948369483794838948399484094841948429484394844948459484694847948489484994850948519485294853948549485594856948579485894859948609486194862948639486494865948669486794868948699487094871948729487394874948759487694877948789487994880948819488294883948849488594886948879488894889948909489194892948939489494895948969489794898948999490094901949029490394904949059490694907949089490994910949119491294913949149491594916949179491894919949209492194922949239492494925949269492794928949299493094931949329493394934949359493694937949389493994940949419494294943949449494594946949479494894949949509495194952949539495494955949569495794958949599496094961949629496394964949659496694967949689496994970949719497294973949749497594976949779497894979949809498194982949839498494985949869498794988949899499094991949929499394994949959499694997949989499995000950019500295003950049500595006950079500895009950109501195012950139501495015950169501795018950199502095021950229502395024950259502695027950289502995030950319503295033950349503595036950379503895039950409504195042950439504495045950469504795048950499505095051950529505395054950559505695057950589505995060950619506295063950649506595066950679506895069950709507195072950739507495075950769507795078950799508095081950829508395084950859508695087950889508995090950919509295093950949509595096950979509895099951009510195102951039510495105951069510795108951099511095111951129511395114951159511695117951189511995120951219512295123951249512595126951279512895129951309513195132951339513495135951369513795138951399514095141951429514395144951459514695147951489514995150951519515295153951549515595156951579515895159951609516195162951639516495165951669516795168951699517095171951729517395174951759517695177951789517995180951819518295183951849518595186951879518895189951909519195192951939519495195951969519795198951999520095201952029520395204952059520695207952089520995210952119521295213952149521595216952179521895219952209522195222952239522495225952269522795228952299523095231952329523395234952359523695237952389523995240952419524295243952449524595246952479524895249952509525195252952539525495255952569525795258952599526095261952629526395264952659526695267952689526995270952719527295273952749527595276952779527895279952809528195282952839528495285952869528795288952899529095291952929529395294952959529695297952989529995300953019530295303953049530595306953079530895309953109531195312953139531495315953169531795318953199532095321953229532395324953259532695327953289532995330953319533295333953349533595336953379533895339953409534195342953439534495345953469534795348953499535095351953529535395354953559535695357953589535995360953619536295363953649536595366953679536895369953709537195372953739537495375953769537795378953799538095381953829538395384953859538695387953889538995390953919539295393953949539595396953979539895399954009540195402954039540495405954069540795408954099541095411954129541395414954159541695417954189541995420954219542295423954249542595426954279542895429954309543195432954339543495435954369543795438954399544095441954429544395444954459544695447954489544995450954519545295453954549545595456954579545895459954609546195462954639546495465954669546795468954699547095471954729547395474954759547695477954789547995480954819548295483954849548595486954879548895489954909549195492954939549495495954969549795498954999550095501955029550395504955059550695507955089550995510955119551295513955149551595516955179551895519955209552195522955239552495525955269552795528955299553095531955329553395534955359553695537955389553995540955419554295543955449554595546955479554895549955509555195552955539555495555955569555795558955599556095561955629556395564955659556695567955689556995570955719557295573955749557595576955779557895579955809558195582955839558495585955869558795588
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. 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) {
  77. continue;
  78. }
  79. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  80. continue;
  81. }
  82. if (otherMesh.material.getEffect() === effect) {
  83. otherMesh.computeBonesUsingShaders = false;
  84. }
  85. else {
  86. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  87. var subMesh = _a[_i];
  88. var subMeshEffect = subMesh.effect;
  89. if (subMeshEffect === effect) {
  90. otherMesh.computeBonesUsingShaders = false;
  91. break;
  92. }
  93. }
  94. }
  95. }
  96. }
  97. else {
  98. var currentFallbacks = this._defines[this._currentRank];
  99. if (currentFallbacks) {
  100. for (var index = 0; index < currentFallbacks.length; index++) {
  101. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  102. }
  103. }
  104. this._currentRank++;
  105. }
  106. return currentDefines;
  107. };
  108. return EffectFallbacks;
  109. }());
  110. BABYLON.EffectFallbacks = EffectFallbacks;
  111. /**
  112. * Options to be used when creating an effect.
  113. */
  114. var EffectCreationOptions = /** @class */ (function () {
  115. function EffectCreationOptions() {
  116. }
  117. return EffectCreationOptions;
  118. }());
  119. BABYLON.EffectCreationOptions = EffectCreationOptions;
  120. /**
  121. * Effect containing vertex and fragment shader that can be executed on an object.
  122. */
  123. var Effect = /** @class */ (function () {
  124. /**
  125. * Instantiates an effect.
  126. * An effect can be used to create/manage/execute vertex and fragment shaders.
  127. * @param baseName Name of the effect.
  128. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  129. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  130. * @param samplers List of sampler variables that will be passed to the shader.
  131. * @param engine Engine to be used to render the effect
  132. * @param defines Define statements to be added to the shader.
  133. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  134. * @param onCompiled Callback that will be called when the shader is compiled.
  135. * @param onError Callback that will be called if an error occurs during shader compilation.
  136. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  137. */
  138. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  139. if (samplers === void 0) { samplers = null; }
  140. if (defines === void 0) { defines = null; }
  141. if (fallbacks === void 0) { fallbacks = null; }
  142. if (onCompiled === void 0) { onCompiled = null; }
  143. if (onError === void 0) { onError = null; }
  144. var _this = this;
  145. /**
  146. * Unique ID of the effect.
  147. */
  148. this.uniqueId = 0;
  149. /**
  150. * Observable that will be called when the shader is compiled.
  151. */
  152. this.onCompileObservable = new BABYLON.Observable();
  153. /**
  154. * Observable that will be called if an error occurs during shader compilation.
  155. */
  156. this.onErrorObservable = new BABYLON.Observable();
  157. /**
  158. * Observable that will be called when effect is bound.
  159. */
  160. this.onBindObservable = new BABYLON.Observable();
  161. this._uniformBuffersNames = {};
  162. this._isReady = false;
  163. this._compilationError = "";
  164. this.name = baseName;
  165. if (attributesNamesOrOptions.attributes) {
  166. var options = attributesNamesOrOptions;
  167. this._engine = uniformsNamesOrEngine;
  168. this._attributesNames = options.attributes;
  169. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  170. this._samplers = options.samplers;
  171. this.defines = options.defines;
  172. this.onError = options.onError;
  173. this.onCompiled = options.onCompiled;
  174. this._fallbacks = options.fallbacks;
  175. this._indexParameters = options.indexParameters;
  176. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  177. if (options.uniformBuffersNames) {
  178. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  179. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  180. }
  181. }
  182. }
  183. else {
  184. this._engine = engine;
  185. this.defines = defines;
  186. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  187. this._samplers = samplers;
  188. this._attributesNames = attributesNamesOrOptions;
  189. this.onError = onError;
  190. this.onCompiled = onCompiled;
  191. this._indexParameters = indexParameters;
  192. this._fallbacks = fallbacks;
  193. }
  194. this.uniqueId = Effect._uniqueIdSeed++;
  195. if (this._getFromCache(baseName)) {
  196. this._prepareEffect();
  197. return;
  198. }
  199. var vertexSource;
  200. var fragmentSource;
  201. if (baseName.vertexElement) {
  202. vertexSource = document.getElementById(baseName.vertexElement);
  203. if (!vertexSource) {
  204. vertexSource = baseName.vertexElement;
  205. }
  206. }
  207. else {
  208. vertexSource = baseName.vertex || baseName;
  209. }
  210. if (baseName.fragmentElement) {
  211. fragmentSource = document.getElementById(baseName.fragmentElement);
  212. if (!fragmentSource) {
  213. fragmentSource = baseName.fragmentElement;
  214. }
  215. }
  216. else {
  217. fragmentSource = baseName.fragment || baseName;
  218. }
  219. var finalVertexCode;
  220. this._loadVertexShaderAsync(vertexSource)
  221. .then(function (vertexCode) {
  222. return _this._processIncludesAsync(vertexCode);
  223. })
  224. .then(function (vertexCodeWithIncludes) {
  225. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  226. return _this._loadFragmentShaderAsync(fragmentSource);
  227. })
  228. .then(function (fragmentCode) {
  229. return _this._processIncludesAsync(fragmentCode);
  230. })
  231. .then(function (fragmentCodeWithIncludes) {
  232. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  233. if (baseName) {
  234. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  235. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  236. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  237. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  238. }
  239. else {
  240. _this._vertexSourceCode = finalVertexCode;
  241. _this._fragmentSourceCode = migratedFragmentCode;
  242. }
  243. _this._setInCache(baseName);
  244. _this._prepareEffect();
  245. });
  246. }
  247. Effect.prototype._getSourceCacheKey = function (baseName) {
  248. var cacheKey = baseName;
  249. if (this._indexParameters) {
  250. for (var key in this._indexParameters) {
  251. if (this._indexParameters.hasOwnProperty(key)) {
  252. cacheKey += "|";
  253. cacheKey += key;
  254. cacheKey += "_";
  255. cacheKey += this._indexParameters[key];
  256. }
  257. }
  258. }
  259. return cacheKey;
  260. };
  261. Effect.prototype._getFromCache = function (baseName) {
  262. if (typeof baseName !== "string") {
  263. return false;
  264. }
  265. var cacheKey = this._getSourceCacheKey(baseName);
  266. var sources = Effect._sourceCache[cacheKey];
  267. if (!sources) {
  268. return false;
  269. }
  270. this._vertexSourceCode = sources.vertex;
  271. this._fragmentSourceCode = sources.fragment;
  272. return true;
  273. };
  274. Effect.prototype._setInCache = function (baseName) {
  275. if (typeof baseName !== "string") {
  276. return;
  277. }
  278. var cacheKey = this._getSourceCacheKey(baseName);
  279. Effect._sourceCache[cacheKey] = {
  280. vertex: this._vertexSourceCode,
  281. fragment: this._fragmentSourceCode
  282. };
  283. };
  284. Object.defineProperty(Effect.prototype, "key", {
  285. /**
  286. * Unique key for this effect
  287. */
  288. get: function () {
  289. return this._key;
  290. },
  291. enumerable: true,
  292. configurable: true
  293. });
  294. /**
  295. * If the effect has been compiled and prepared.
  296. * @returns if the effect is compiled and prepared.
  297. */
  298. Effect.prototype.isReady = function () {
  299. return this._isReady;
  300. };
  301. /**
  302. * The engine the effect was initialized with.
  303. * @returns the engine.
  304. */
  305. Effect.prototype.getEngine = function () {
  306. return this._engine;
  307. };
  308. /**
  309. * The compiled webGL program for the effect
  310. * @returns the webGL program.
  311. */
  312. Effect.prototype.getProgram = function () {
  313. return this._program;
  314. };
  315. /**
  316. * The set of names of attribute variables for the shader.
  317. * @returns An array of attribute names.
  318. */
  319. Effect.prototype.getAttributesNames = function () {
  320. return this._attributesNames;
  321. };
  322. /**
  323. * Returns the attribute at the given index.
  324. * @param index The index of the attribute.
  325. * @returns The location of the attribute.
  326. */
  327. Effect.prototype.getAttributeLocation = function (index) {
  328. return this._attributes[index];
  329. };
  330. /**
  331. * Returns the attribute based on the name of the variable.
  332. * @param name of the attribute to look up.
  333. * @returns the attribute location.
  334. */
  335. Effect.prototype.getAttributeLocationByName = function (name) {
  336. var index = this._attributesNames.indexOf(name);
  337. return this._attributes[index];
  338. };
  339. /**
  340. * The number of attributes.
  341. * @returns the numnber of attributes.
  342. */
  343. Effect.prototype.getAttributesCount = function () {
  344. return this._attributes.length;
  345. };
  346. /**
  347. * Gets the index of a uniform variable.
  348. * @param uniformName of the uniform to look up.
  349. * @returns the index.
  350. */
  351. Effect.prototype.getUniformIndex = function (uniformName) {
  352. return this._uniformsNames.indexOf(uniformName);
  353. };
  354. /**
  355. * Returns the attribute based on the name of the variable.
  356. * @param uniformName of the uniform to look up.
  357. * @returns the location of the uniform.
  358. */
  359. Effect.prototype.getUniform = function (uniformName) {
  360. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  361. };
  362. /**
  363. * Returns an array of sampler variable names
  364. * @returns The array of sampler variable neames.
  365. */
  366. Effect.prototype.getSamplers = function () {
  367. return this._samplers;
  368. };
  369. /**
  370. * The error from the last compilation.
  371. * @returns the error string.
  372. */
  373. Effect.prototype.getCompilationError = function () {
  374. return this._compilationError;
  375. };
  376. /**
  377. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  378. * @param func The callback to be used.
  379. */
  380. Effect.prototype.executeWhenCompiled = function (func) {
  381. if (this.isReady()) {
  382. func(this);
  383. return;
  384. }
  385. this.onCompileObservable.add(function (effect) {
  386. func(effect);
  387. });
  388. };
  389. /** @ignore */
  390. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  391. if (BABYLON.Tools.IsWindowObjectExist()) {
  392. // DOM element ?
  393. if (vertex instanceof HTMLElement) {
  394. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  395. return Promise.resolve(vertexCode);
  396. }
  397. }
  398. // Base64 encoded ?
  399. if (vertex.substr(0, 7) === "base64:") {
  400. var vertexBinary = window.atob(vertex.substr(7));
  401. return Promise.resolve(vertexBinary);
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  405. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  406. }
  407. var vertexShaderUrl;
  408. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  409. vertexShaderUrl = vertex;
  410. }
  411. else {
  412. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  413. }
  414. // Vertex shader
  415. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  416. };
  417. /** @ignore */
  418. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  419. if (BABYLON.Tools.IsWindowObjectExist()) {
  420. // DOM element ?
  421. if (fragment instanceof HTMLElement) {
  422. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  423. return Promise.resolve(fragmentCode);
  424. }
  425. }
  426. // Base64 encoded ?
  427. if (fragment.substr(0, 7) === "base64:") {
  428. var fragmentBinary = window.atob(fragment.substr(7));
  429. return Promise.resolve(fragmentBinary);
  430. }
  431. // Is in local store ?
  432. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  433. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  434. }
  435. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  436. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  437. }
  438. var fragmentShaderUrl;
  439. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  440. fragmentShaderUrl = fragment;
  441. }
  442. else {
  443. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  444. }
  445. // Fragment shader
  446. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  447. };
  448. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  449. // Rebuild shaders source code
  450. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  451. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  452. vertexCode = prefix + vertexCode;
  453. fragmentCode = prefix + fragmentCode;
  454. // Number lines of shaders source code
  455. var i = 2;
  456. var regex = /\n/gm;
  457. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  458. i = 2;
  459. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  460. // Dump shaders name and formatted source code
  461. if (this.name.vertexElement) {
  462. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  463. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  464. }
  465. else if (this.name.vertex) {
  466. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  467. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  468. }
  469. else {
  470. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  471. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  472. }
  473. };
  474. ;
  475. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  476. var preparedSourceCode = this._processPrecision(sourceCode);
  477. if (this._engine.webGLVersion == 1) {
  478. return preparedSourceCode;
  479. }
  480. // Already converted
  481. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  482. return preparedSourceCode.replace("#version 300 es", "");
  483. }
  484. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  485. // Remove extensions
  486. // #extension GL_OES_standard_derivatives : enable
  487. // #extension GL_EXT_shader_texture_lod : enable
  488. // #extension GL_EXT_frag_depth : enable
  489. // #extension GL_EXT_draw_buffers : require
  490. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  491. var result = preparedSourceCode.replace(regex, "");
  492. // Migrate to GLSL v300
  493. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  494. result = result.replace(/attribute[ \t]/g, "in ");
  495. result = result.replace(/[ \t]attribute/g, " in");
  496. if (isFragment) {
  497. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  498. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  499. result = result.replace(/texture2D\s*\(/g, "texture(");
  500. result = result.replace(/textureCube\s*\(/g, "texture(");
  501. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  502. result = result.replace(/gl_FragColor/g, "glFragColor");
  503. result = result.replace(/gl_FragData/g, "glFragData");
  504. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  505. }
  506. return result;
  507. };
  508. Effect.prototype._processIncludesAsync = function (sourceCode) {
  509. var _this = this;
  510. return new Promise(function (resolve, reject) {
  511. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  512. var match = regex.exec(sourceCode);
  513. var returnValue = sourceCode;
  514. while (match != null) {
  515. var includeFile = match[1];
  516. // Uniform declaration
  517. if (includeFile.indexOf("__decl__") !== -1) {
  518. includeFile = includeFile.replace(/__decl__/, "");
  519. if (_this._engine.supportsUniformBuffers) {
  520. includeFile = includeFile.replace(/Vertex/, "Ubo");
  521. includeFile = includeFile.replace(/Fragment/, "Ubo");
  522. }
  523. includeFile = includeFile + "Declaration";
  524. }
  525. if (Effect.IncludesShadersStore[includeFile]) {
  526. // Substitution
  527. var includeContent = Effect.IncludesShadersStore[includeFile];
  528. if (match[2]) {
  529. var splits = match[3].split(",");
  530. for (var index = 0; index < splits.length; index += 2) {
  531. var source = new RegExp(splits[index], "g");
  532. var dest = splits[index + 1];
  533. includeContent = includeContent.replace(source, dest);
  534. }
  535. }
  536. if (match[4]) {
  537. var indexString = match[5];
  538. if (indexString.indexOf("..") !== -1) {
  539. var indexSplits = indexString.split("..");
  540. var minIndex = parseInt(indexSplits[0]);
  541. var maxIndex = parseInt(indexSplits[1]);
  542. var sourceIncludeContent = includeContent.slice(0);
  543. includeContent = "";
  544. if (isNaN(maxIndex)) {
  545. maxIndex = _this._indexParameters[indexSplits[1]];
  546. }
  547. for (var i = minIndex; i < maxIndex; i++) {
  548. if (!_this._engine.supportsUniformBuffers) {
  549. // Ubo replacement
  550. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  551. return p1 + "{X}";
  552. });
  553. }
  554. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  555. }
  556. }
  557. else {
  558. if (!_this._engine.supportsUniformBuffers) {
  559. // Ubo replacement
  560. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  561. return p1 + "{X}";
  562. });
  563. }
  564. includeContent = includeContent.replace(/\{X\}/g, indexString);
  565. }
  566. }
  567. // Replace
  568. returnValue = returnValue.replace(match[0], includeContent);
  569. }
  570. else {
  571. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  572. _this._engine._loadFileAsync(includeShaderUrl)
  573. .then(function (fileContent) {
  574. Effect.IncludesShadersStore[includeFile] = fileContent;
  575. return _this._processIncludesAsync(returnValue);
  576. })
  577. .then(function (returnValue) {
  578. resolve(returnValue);
  579. });
  580. return;
  581. }
  582. match = regex.exec(sourceCode);
  583. }
  584. resolve(returnValue);
  585. });
  586. };
  587. Effect.prototype._processPrecision = function (source) {
  588. if (source.indexOf("precision highp float") === -1) {
  589. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  590. source = "precision mediump float;\n" + source;
  591. }
  592. else {
  593. source = "precision highp float;\n" + source;
  594. }
  595. }
  596. else {
  597. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  598. source = source.replace("precision highp float", "precision mediump float");
  599. }
  600. }
  601. return source;
  602. };
  603. /**
  604. * Recompiles the webGL program
  605. * @param vertexSourceCode The source code for the vertex shader.
  606. * @param fragmentSourceCode The source code for the fragment shader.
  607. * @param onCompiled Callback called when completed.
  608. * @param onError Callback called on error.
  609. */
  610. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  611. var _this = this;
  612. this._isReady = false;
  613. this._vertexSourceCodeOverride = vertexSourceCode;
  614. this._fragmentSourceCodeOverride = fragmentSourceCode;
  615. this.onError = function (effect, error) {
  616. if (onError) {
  617. onError(error);
  618. }
  619. };
  620. this.onCompiled = function () {
  621. var scenes = _this.getEngine().scenes;
  622. for (var i = 0; i < scenes.length; i++) {
  623. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  624. }
  625. if (onCompiled) {
  626. onCompiled(_this._program);
  627. }
  628. };
  629. this._fallbacks = null;
  630. this._prepareEffect();
  631. };
  632. /**
  633. * Gets the uniform locations of the the specified variable names
  634. * @param names THe names of the variables to lookup.
  635. * @returns Array of locations in the same order as variable names.
  636. */
  637. Effect.prototype.getSpecificUniformLocations = function (names) {
  638. var engine = this._engine;
  639. return engine.getUniforms(this._program, names);
  640. };
  641. /**
  642. * Prepares the effect
  643. */
  644. Effect.prototype._prepareEffect = function () {
  645. var attributesNames = this._attributesNames;
  646. var defines = this.defines;
  647. var fallbacks = this._fallbacks;
  648. this._valueCache = {};
  649. var previousProgram = this._program;
  650. try {
  651. var engine = this._engine;
  652. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  653. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  654. }
  655. else {
  656. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  657. }
  658. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  659. if (engine.supportsUniformBuffers) {
  660. for (var name in this._uniformBuffersNames) {
  661. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  662. }
  663. }
  664. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  665. this._attributes = engine.getAttributes(this._program, attributesNames);
  666. var index;
  667. for (index = 0; index < this._samplers.length; index++) {
  668. var sampler = this.getUniform(this._samplers[index]);
  669. if (sampler == null) {
  670. this._samplers.splice(index, 1);
  671. index--;
  672. }
  673. }
  674. engine.bindSamplers(this);
  675. this._compilationError = "";
  676. this._isReady = true;
  677. if (this.onCompiled) {
  678. this.onCompiled(this);
  679. }
  680. this.onCompileObservable.notifyObservers(this);
  681. this.onCompileObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. if (previousProgram) {
  687. this.getEngine()._deleteProgram(previousProgram);
  688. }
  689. }
  690. catch (e) {
  691. this._compilationError = e.message;
  692. // Let's go through fallbacks then
  693. BABYLON.Tools.Error("Unable to compile effect:");
  694. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  695. return " " + uniform;
  696. }));
  697. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  698. return " " + attribute;
  699. }));
  700. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  701. BABYLON.Tools.Error("Error: " + this._compilationError);
  702. if (previousProgram) {
  703. this._program = previousProgram;
  704. this._isReady = true;
  705. if (this.onError) {
  706. this.onError(this, this._compilationError);
  707. }
  708. this.onErrorObservable.notifyObservers(this);
  709. }
  710. if (fallbacks && fallbacks.isMoreFallbacks) {
  711. BABYLON.Tools.Error("Trying next fallback.");
  712. this.defines = fallbacks.reduce(this.defines, this);
  713. this._prepareEffect();
  714. }
  715. else {
  716. if (this.onError) {
  717. this.onError(this, this._compilationError);
  718. }
  719. this.onErrorObservable.notifyObservers(this);
  720. this.onErrorObservable.clear();
  721. // Unbind mesh reference in fallbacks
  722. if (this._fallbacks) {
  723. this._fallbacks.unBindMesh();
  724. }
  725. }
  726. }
  727. };
  728. Object.defineProperty(Effect.prototype, "isSupported", {
  729. /**
  730. * Checks if the effect is supported. (Must be called after compilation)
  731. */
  732. get: function () {
  733. return this._compilationError === "";
  734. },
  735. enumerable: true,
  736. configurable: true
  737. });
  738. /**
  739. * Binds a texture to the engine to be used as output of the shader.
  740. * @param channel Name of the output variable.
  741. * @param texture Texture to bind.
  742. */
  743. Effect.prototype._bindTexture = function (channel, texture) {
  744. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  745. };
  746. /**
  747. * Sets a texture on the engine to be used in the shader.
  748. * @param channel Name of the sampler variable.
  749. * @param texture Texture to set.
  750. */
  751. Effect.prototype.setTexture = function (channel, texture) {
  752. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  753. };
  754. /**
  755. * Sets an array of textures on the engine to be used in the shader.
  756. * @param channel Name of the variable.
  757. * @param textures Textures to set.
  758. */
  759. Effect.prototype.setTextureArray = function (channel, textures) {
  760. if (this._samplers.indexOf(channel + "Ex") === -1) {
  761. var initialPos = this._samplers.indexOf(channel);
  762. for (var index = 1; index < textures.length; index++) {
  763. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  764. }
  765. }
  766. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  767. };
  768. /**
  769. * 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)
  770. * @param channel Name of the sampler variable.
  771. * @param postProcess Post process to get the input texture from.
  772. */
  773. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  774. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  775. };
  776. /** @ignore */
  777. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  778. var cache = this._valueCache[uniformName];
  779. var flag = matrix.updateFlag;
  780. if (cache !== undefined && cache === flag) {
  781. return false;
  782. }
  783. this._valueCache[uniformName] = flag;
  784. return true;
  785. };
  786. /** @ignore */
  787. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  788. var cache = this._valueCache[uniformName];
  789. if (!cache) {
  790. cache = [x, y];
  791. this._valueCache[uniformName] = cache;
  792. return true;
  793. }
  794. var changed = false;
  795. if (cache[0] !== x) {
  796. cache[0] = x;
  797. changed = true;
  798. }
  799. if (cache[1] !== y) {
  800. cache[1] = y;
  801. changed = true;
  802. }
  803. return changed;
  804. };
  805. /** @ignore */
  806. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  807. var cache = this._valueCache[uniformName];
  808. if (!cache) {
  809. cache = [x, y, z];
  810. this._valueCache[uniformName] = cache;
  811. return true;
  812. }
  813. var changed = false;
  814. if (cache[0] !== x) {
  815. cache[0] = x;
  816. changed = true;
  817. }
  818. if (cache[1] !== y) {
  819. cache[1] = y;
  820. changed = true;
  821. }
  822. if (cache[2] !== z) {
  823. cache[2] = z;
  824. changed = true;
  825. }
  826. return changed;
  827. };
  828. /** @ignore */
  829. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  830. var cache = this._valueCache[uniformName];
  831. if (!cache) {
  832. cache = [x, y, z, w];
  833. this._valueCache[uniformName] = cache;
  834. return true;
  835. }
  836. var changed = false;
  837. if (cache[0] !== x) {
  838. cache[0] = x;
  839. changed = true;
  840. }
  841. if (cache[1] !== y) {
  842. cache[1] = y;
  843. changed = true;
  844. }
  845. if (cache[2] !== z) {
  846. cache[2] = z;
  847. changed = true;
  848. }
  849. if (cache[3] !== w) {
  850. cache[3] = w;
  851. changed = true;
  852. }
  853. return changed;
  854. };
  855. /**
  856. * Binds a buffer to a uniform.
  857. * @param buffer Buffer to bind.
  858. * @param name Name of the uniform variable to bind to.
  859. */
  860. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  861. var bufferName = this._uniformBuffersNames[name];
  862. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  863. return;
  864. }
  865. Effect._baseCache[bufferName] = buffer;
  866. this._engine.bindUniformBufferBase(buffer, bufferName);
  867. };
  868. /**
  869. * Binds block to a uniform.
  870. * @param blockName Name of the block to bind.
  871. * @param index Index to bind.
  872. */
  873. Effect.prototype.bindUniformBlock = function (blockName, index) {
  874. this._engine.bindUniformBlock(this._program, blockName, index);
  875. };
  876. /**
  877. * Sets an interger value on a uniform variable.
  878. * @param uniformName Name of the variable.
  879. * @param value Value to be set.
  880. * @returns this effect.
  881. */
  882. Effect.prototype.setInt = function (uniformName, value) {
  883. var cache = this._valueCache[uniformName];
  884. if (cache !== undefined && cache === value)
  885. return this;
  886. this._valueCache[uniformName] = value;
  887. this._engine.setInt(this.getUniform(uniformName), value);
  888. return this;
  889. };
  890. /**
  891. * Sets an int array on a uniform variable.
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * 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)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray2 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray2(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * 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)
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setIntArray3 = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setIntArray3(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * 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)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setIntArray4 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setIntArray4(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * Sets an float array on a uniform variable.
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * 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)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * 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)
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * 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)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * Sets an array on a uniform variable.
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * 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)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray2 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray2(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * 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)
  1002. * @param uniformName Name of the variable.
  1003. * @param array array to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setArray3 = function (uniformName, array) {
  1007. this._valueCache[uniformName] = null;
  1008. this._engine.setArray3(this.getUniform(uniformName), array);
  1009. return this;
  1010. };
  1011. /**
  1012. * 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)
  1013. * @param uniformName Name of the variable.
  1014. * @param array array to be set.
  1015. * @returns this effect.
  1016. */
  1017. Effect.prototype.setArray4 = function (uniformName, array) {
  1018. this._valueCache[uniformName] = null;
  1019. this._engine.setArray4(this.getUniform(uniformName), array);
  1020. return this;
  1021. };
  1022. /**
  1023. * Sets matrices on a uniform variable.
  1024. * @param uniformName Name of the variable.
  1025. * @param matrices matrices to be set.
  1026. * @returns this effect.
  1027. */
  1028. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1029. if (!matrices) {
  1030. return this;
  1031. }
  1032. this._valueCache[uniformName] = null;
  1033. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1034. return this;
  1035. };
  1036. /**
  1037. * Sets matrix on a uniform variable.
  1038. * @param uniformName Name of the variable.
  1039. * @param matrix matrix to be set.
  1040. * @returns this effect.
  1041. */
  1042. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1043. if (this._cacheMatrix(uniformName, matrix)) {
  1044. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1045. }
  1046. return this;
  1047. };
  1048. /**
  1049. * 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)
  1050. * @param uniformName Name of the variable.
  1051. * @param matrix matrix to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1055. this._valueCache[uniformName] = null;
  1056. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1057. return this;
  1058. };
  1059. /**
  1060. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1061. * @param uniformName Name of the variable.
  1062. * @param matrix matrix to be set.
  1063. * @returns this effect.
  1064. */
  1065. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1066. this._valueCache[uniformName] = null;
  1067. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1068. return this;
  1069. };
  1070. /**
  1071. * Sets a float on a uniform variable.
  1072. * @param uniformName Name of the variable.
  1073. * @param value value to be set.
  1074. * @returns this effect.
  1075. */
  1076. Effect.prototype.setFloat = function (uniformName, value) {
  1077. var cache = this._valueCache[uniformName];
  1078. if (cache !== undefined && cache === value)
  1079. return this;
  1080. this._valueCache[uniformName] = value;
  1081. this._engine.setFloat(this.getUniform(uniformName), value);
  1082. return this;
  1083. };
  1084. /**
  1085. * Sets a boolean on a uniform variable.
  1086. * @param uniformName Name of the variable.
  1087. * @param bool value to be set.
  1088. * @returns this effect.
  1089. */
  1090. Effect.prototype.setBool = function (uniformName, bool) {
  1091. var cache = this._valueCache[uniformName];
  1092. if (cache !== undefined && cache === bool)
  1093. return this;
  1094. this._valueCache[uniformName] = bool;
  1095. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1096. return this;
  1097. };
  1098. /**
  1099. * Sets a Vector2 on a uniform variable.
  1100. * @param uniformName Name of the variable.
  1101. * @param vector2 vector2 to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1105. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1106. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1107. }
  1108. return this;
  1109. };
  1110. /**
  1111. * Sets a float2 on a uniform variable.
  1112. * @param uniformName Name of the variable.
  1113. * @param x First float in float2.
  1114. * @param y Second float in float2.
  1115. * @returns this effect.
  1116. */
  1117. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1118. if (this._cacheFloat2(uniformName, x, y)) {
  1119. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1120. }
  1121. return this;
  1122. };
  1123. /**
  1124. * Sets a Vector3 on a uniform variable.
  1125. * @param uniformName Name of the variable.
  1126. * @param vector3 Value to be set.
  1127. * @returns this effect.
  1128. */
  1129. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1130. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1131. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1132. }
  1133. return this;
  1134. };
  1135. /**
  1136. * Sets a float3 on a uniform variable.
  1137. * @param uniformName Name of the variable.
  1138. * @param x First float in float3.
  1139. * @param y Second float in float3.
  1140. * @param z Third float in float3.
  1141. * @returns this effect.
  1142. */
  1143. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1144. if (this._cacheFloat3(uniformName, x, y, z)) {
  1145. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1146. }
  1147. return this;
  1148. };
  1149. /**
  1150. * Sets a Vector4 on a uniform variable.
  1151. * @param uniformName Name of the variable.
  1152. * @param vector4 Value to be set.
  1153. * @returns this effect.
  1154. */
  1155. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1156. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1157. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1158. }
  1159. return this;
  1160. };
  1161. /**
  1162. * Sets a float4 on a uniform variable.
  1163. * @param uniformName Name of the variable.
  1164. * @param x First float in float4.
  1165. * @param y Second float in float4.
  1166. * @param z Third float in float4.
  1167. * @param w Fourth float in float4.
  1168. * @returns this effect.
  1169. */
  1170. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1171. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1172. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1173. }
  1174. return this;
  1175. };
  1176. /**
  1177. * Sets a Color3 on a uniform variable.
  1178. * @param uniformName Name of the variable.
  1179. * @param color3 Value to be set.
  1180. * @returns this effect.
  1181. */
  1182. Effect.prototype.setColor3 = function (uniformName, color3) {
  1183. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1184. this._engine.setColor3(this.getUniform(uniformName), color3);
  1185. }
  1186. return this;
  1187. };
  1188. /**
  1189. * Sets a Color4 on a uniform variable.
  1190. * @param uniformName Name of the variable.
  1191. * @param color3 Value to be set.
  1192. * @param alpha Alpha value to be set.
  1193. * @returns this effect.
  1194. */
  1195. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1196. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1197. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1198. }
  1199. return this;
  1200. };
  1201. /**
  1202. * Sets a Color4 on a uniform variable
  1203. * @param uniformName defines the name of the variable
  1204. * @param color4 defines the value to be set
  1205. * @returns this effect.
  1206. */
  1207. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1208. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1209. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1210. }
  1211. return this;
  1212. };
  1213. /**
  1214. * Resets the cache of effects.
  1215. */
  1216. Effect.ResetCache = function () {
  1217. Effect._baseCache = {};
  1218. };
  1219. Effect._uniqueIdSeed = 0;
  1220. Effect._baseCache = {};
  1221. Effect._sourceCache = {};
  1222. // Statics
  1223. /**
  1224. * Store of each shader (The can be looked up using effect.key)
  1225. */
  1226. Effect.ShadersStore = {};
  1227. /**
  1228. * Store of each included file for a shader (The can be looked up using effect.key)
  1229. */
  1230. Effect.IncludesShadersStore = {};
  1231. return Effect;
  1232. }());
  1233. BABYLON.Effect = Effect;
  1234. })(BABYLON || (BABYLON = {}));
  1235. //# sourceMappingURL=babylon.effect.js.map
  1236. //# sourceMappingURL=babylon.types.js.map
  1237. var BABYLON;
  1238. (function (BABYLON) {
  1239. var KeyboardEventTypes = /** @class */ (function () {
  1240. function KeyboardEventTypes() {
  1241. }
  1242. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1243. get: function () {
  1244. return KeyboardEventTypes._KEYDOWN;
  1245. },
  1246. enumerable: true,
  1247. configurable: true
  1248. });
  1249. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1250. get: function () {
  1251. return KeyboardEventTypes._KEYUP;
  1252. },
  1253. enumerable: true,
  1254. configurable: true
  1255. });
  1256. KeyboardEventTypes._KEYDOWN = 0x01;
  1257. KeyboardEventTypes._KEYUP = 0x02;
  1258. return KeyboardEventTypes;
  1259. }());
  1260. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1261. var KeyboardInfo = /** @class */ (function () {
  1262. function KeyboardInfo(type, event) {
  1263. this.type = type;
  1264. this.event = event;
  1265. }
  1266. return KeyboardInfo;
  1267. }());
  1268. BABYLON.KeyboardInfo = KeyboardInfo;
  1269. /**
  1270. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1271. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1272. */
  1273. var KeyboardInfoPre = /** @class */ (function (_super) {
  1274. __extends(KeyboardInfoPre, _super);
  1275. function KeyboardInfoPre(type, event) {
  1276. var _this = _super.call(this, type, event) || this;
  1277. _this.skipOnPointerObservable = false;
  1278. return _this;
  1279. }
  1280. return KeyboardInfoPre;
  1281. }(KeyboardInfo));
  1282. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1283. })(BABYLON || (BABYLON = {}));
  1284. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1285. var BABYLON;
  1286. (function (BABYLON) {
  1287. var PointerEventTypes = /** @class */ (function () {
  1288. function PointerEventTypes() {
  1289. }
  1290. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1291. get: function () {
  1292. return PointerEventTypes._POINTERDOWN;
  1293. },
  1294. enumerable: true,
  1295. configurable: true
  1296. });
  1297. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1298. get: function () {
  1299. return PointerEventTypes._POINTERUP;
  1300. },
  1301. enumerable: true,
  1302. configurable: true
  1303. });
  1304. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1305. get: function () {
  1306. return PointerEventTypes._POINTERMOVE;
  1307. },
  1308. enumerable: true,
  1309. configurable: true
  1310. });
  1311. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1312. get: function () {
  1313. return PointerEventTypes._POINTERWHEEL;
  1314. },
  1315. enumerable: true,
  1316. configurable: true
  1317. });
  1318. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1319. get: function () {
  1320. return PointerEventTypes._POINTERPICK;
  1321. },
  1322. enumerable: true,
  1323. configurable: true
  1324. });
  1325. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1326. get: function () {
  1327. return PointerEventTypes._POINTERTAP;
  1328. },
  1329. enumerable: true,
  1330. configurable: true
  1331. });
  1332. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1333. get: function () {
  1334. return PointerEventTypes._POINTERDOUBLETAP;
  1335. },
  1336. enumerable: true,
  1337. configurable: true
  1338. });
  1339. PointerEventTypes._POINTERDOWN = 0x01;
  1340. PointerEventTypes._POINTERUP = 0x02;
  1341. PointerEventTypes._POINTERMOVE = 0x04;
  1342. PointerEventTypes._POINTERWHEEL = 0x08;
  1343. PointerEventTypes._POINTERPICK = 0x10;
  1344. PointerEventTypes._POINTERTAP = 0x20;
  1345. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1346. return PointerEventTypes;
  1347. }());
  1348. BABYLON.PointerEventTypes = PointerEventTypes;
  1349. var PointerInfoBase = /** @class */ (function () {
  1350. function PointerInfoBase(type, event) {
  1351. this.type = type;
  1352. this.event = event;
  1353. }
  1354. return PointerInfoBase;
  1355. }());
  1356. BABYLON.PointerInfoBase = PointerInfoBase;
  1357. /**
  1358. * This class is used to store pointer related info for the onPrePointerObservable event.
  1359. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1360. */
  1361. var PointerInfoPre = /** @class */ (function (_super) {
  1362. __extends(PointerInfoPre, _super);
  1363. function PointerInfoPre(type, event, localX, localY) {
  1364. var _this = _super.call(this, type, event) || this;
  1365. _this.skipOnPointerObservable = false;
  1366. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1367. return _this;
  1368. }
  1369. return PointerInfoPre;
  1370. }(PointerInfoBase));
  1371. BABYLON.PointerInfoPre = PointerInfoPre;
  1372. /**
  1373. * This type contains all the data related to a pointer event in Babylon.js.
  1374. * 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.
  1375. */
  1376. var PointerInfo = /** @class */ (function (_super) {
  1377. __extends(PointerInfo, _super);
  1378. function PointerInfo(type, event, pickInfo) {
  1379. var _this = _super.call(this, type, event) || this;
  1380. _this.pickInfo = pickInfo;
  1381. return _this;
  1382. }
  1383. return PointerInfo;
  1384. }(PointerInfoBase));
  1385. BABYLON.PointerInfo = PointerInfo;
  1386. })(BABYLON || (BABYLON = {}));
  1387. //# sourceMappingURL=babylon.pointerEvents.js.map
  1388. var BABYLON;
  1389. (function (BABYLON) {
  1390. BABYLON.ToGammaSpace = 1 / 2.2;
  1391. BABYLON.ToLinearSpace = 2.2;
  1392. BABYLON.Epsilon = 0.001;
  1393. /**
  1394. * Class used to hold a RBG color
  1395. */
  1396. var Color3 = /** @class */ (function () {
  1397. /**
  1398. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1399. * @param r defines the red component (between 0 and 1, default is 0)
  1400. * @param g defines the green component (between 0 and 1, default is 0)
  1401. * @param b defines the blue component (between 0 and 1, default is 0)
  1402. */
  1403. function Color3(
  1404. /**
  1405. * Defines the red component (between 0 and 1, default is 0)
  1406. */
  1407. r,
  1408. /**
  1409. * Defines the green component (between 0 and 1, default is 0)
  1410. */
  1411. g,
  1412. /**
  1413. * Defines the blue component (between 0 and 1, default is 0)
  1414. */
  1415. b) {
  1416. if (r === void 0) { r = 0; }
  1417. if (g === void 0) { g = 0; }
  1418. if (b === void 0) { b = 0; }
  1419. this.r = r;
  1420. this.g = g;
  1421. this.b = b;
  1422. }
  1423. /**
  1424. * Creates a string with the Color3 current values
  1425. * @returns the string representation of the Color3 object
  1426. */
  1427. Color3.prototype.toString = function () {
  1428. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1429. };
  1430. /**
  1431. * Returns the string "Color3"
  1432. * @returns "Color3"
  1433. */
  1434. Color3.prototype.getClassName = function () {
  1435. return "Color3";
  1436. };
  1437. /**
  1438. * Compute the Color3 hash code
  1439. * @returns an unique number that can be used to hash Color3 objects
  1440. */
  1441. Color3.prototype.getHashCode = function () {
  1442. var hash = this.r || 0;
  1443. hash = (hash * 397) ^ (this.g || 0);
  1444. hash = (hash * 397) ^ (this.b || 0);
  1445. return hash;
  1446. };
  1447. // Operators
  1448. /**
  1449. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1450. * @param array defines the array where to store the r,g,b components
  1451. * @param index defines an optional index in the target array to define where to start storing values
  1452. * @returns the current Color3 object
  1453. */
  1454. Color3.prototype.toArray = function (array, index) {
  1455. if (index === undefined) {
  1456. index = 0;
  1457. }
  1458. array[index] = this.r;
  1459. array[index + 1] = this.g;
  1460. array[index + 2] = this.b;
  1461. return this;
  1462. };
  1463. /**
  1464. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1465. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1466. * @returns a new {BABYLON.Color4} object
  1467. */
  1468. Color3.prototype.toColor4 = function (alpha) {
  1469. if (alpha === void 0) { alpha = 1; }
  1470. return new Color4(this.r, this.g, this.b, alpha);
  1471. };
  1472. /**
  1473. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1474. * @returns the new array
  1475. */
  1476. Color3.prototype.asArray = function () {
  1477. var result = new Array();
  1478. this.toArray(result, 0);
  1479. return result;
  1480. };
  1481. /**
  1482. * Returns the luminance value
  1483. * @returns a float value
  1484. */
  1485. Color3.prototype.toLuminance = function () {
  1486. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1487. };
  1488. /**
  1489. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1490. * @param otherColor defines the second operand
  1491. * @returns the new Color3 object
  1492. */
  1493. Color3.prototype.multiply = function (otherColor) {
  1494. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1495. };
  1496. /**
  1497. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1498. * @param otherColor defines the second operand
  1499. * @param result defines the Color3 object where to store the result
  1500. * @returns the current Color3
  1501. */
  1502. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1503. result.r = this.r * otherColor.r;
  1504. result.g = this.g * otherColor.g;
  1505. result.b = this.b * otherColor.b;
  1506. return this;
  1507. };
  1508. /**
  1509. * Determines equality between Color3 objects
  1510. * @param otherColor defines the second operand
  1511. * @returns true if the rgb values are equal to the passed ones
  1512. */
  1513. Color3.prototype.equals = function (otherColor) {
  1514. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1515. };
  1516. /**
  1517. * Determines equality between the current Color3 object and a set of r,b,g values
  1518. * @param r defines the red component to check
  1519. * @param g defines the green component to check
  1520. * @param b defines the blue component to check
  1521. * @returns true if the rgb values are equal to the passed ones
  1522. */
  1523. Color3.prototype.equalsFloats = function (r, g, b) {
  1524. return this.r === r && this.g === g && this.b === b;
  1525. };
  1526. /**
  1527. * Multiplies in place each rgb value by scale
  1528. * @param scale defines the scaling factor
  1529. * @returns the updated Color3.
  1530. */
  1531. Color3.prototype.scale = function (scale) {
  1532. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1533. };
  1534. /**
  1535. * Multiplies the rgb values by scale and stores the result into "result"
  1536. * @param scale defines the scaling factor
  1537. * @param result defines the Color3 object where to store the result
  1538. * @returns the unmodified current Color3.
  1539. */
  1540. Color3.prototype.scaleToRef = function (scale, result) {
  1541. result.r = this.r * scale;
  1542. result.g = this.g * scale;
  1543. result.b = this.b * scale;
  1544. return this;
  1545. };
  1546. /**
  1547. * Clamps the rgb values by the min and max values and stores the result into "result"
  1548. * @param min defines minimum clamping value (default is 0)
  1549. * @param max defines maximum clamping value (default is 1)
  1550. * @param result defines color to store the result into
  1551. * @returns the original Color3
  1552. */
  1553. Color3.prototype.clampToRef = function (min, max, result) {
  1554. if (min === void 0) { min = 0; }
  1555. if (max === void 0) { max = 1; }
  1556. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1557. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1558. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1559. return this;
  1560. };
  1561. /**
  1562. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1563. * @param otherColor defines the second operand
  1564. * @returns the new Color3
  1565. */
  1566. Color3.prototype.add = function (otherColor) {
  1567. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1568. };
  1569. /**
  1570. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1571. * @param otherColor defines the second operand
  1572. * @param result defines Color3 object to store the result into
  1573. * @returns the unmodified current Color3
  1574. */
  1575. Color3.prototype.addToRef = function (otherColor, result) {
  1576. result.r = this.r + otherColor.r;
  1577. result.g = this.g + otherColor.g;
  1578. result.b = this.b + otherColor.b;
  1579. return this;
  1580. };
  1581. /**
  1582. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1583. * @param otherColor defines the second operand
  1584. * @returns the new Color3
  1585. */
  1586. Color3.prototype.subtract = function (otherColor) {
  1587. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1588. };
  1589. /**
  1590. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1591. * @param otherColor defines the second operand
  1592. * @param result defines Color3 object to store the result into
  1593. * @returns the unmodified current Color3
  1594. */
  1595. Color3.prototype.subtractToRef = function (otherColor, result) {
  1596. result.r = this.r - otherColor.r;
  1597. result.g = this.g - otherColor.g;
  1598. result.b = this.b - otherColor.b;
  1599. return this;
  1600. };
  1601. /**
  1602. * Copy the current object
  1603. * @returns a new Color3 copied the current one
  1604. */
  1605. Color3.prototype.clone = function () {
  1606. return new Color3(this.r, this.g, this.b);
  1607. };
  1608. /**
  1609. * Copies the rgb values from the source in the current Color3
  1610. * @param source defines the source Color3 object
  1611. * @returns the updated Color3 object
  1612. */
  1613. Color3.prototype.copyFrom = function (source) {
  1614. this.r = source.r;
  1615. this.g = source.g;
  1616. this.b = source.b;
  1617. return this;
  1618. };
  1619. /**
  1620. * Updates the Color3 rgb values from the passed floats
  1621. * @param r defines the red component to read from
  1622. * @param g defines the green component to read from
  1623. * @param b defines the blue component to read from
  1624. * @returns the current Color3 object
  1625. */
  1626. Color3.prototype.copyFromFloats = function (r, g, b) {
  1627. this.r = r;
  1628. this.g = g;
  1629. this.b = b;
  1630. return this;
  1631. };
  1632. /**
  1633. * Updates the Color3 rgb values from the passed floats
  1634. * @param r defines the red component to read from
  1635. * @param g defines the green component to read from
  1636. * @param b defines the blue component to read from
  1637. * @returns the current Color3 object
  1638. */
  1639. Color3.prototype.set = function (r, g, b) {
  1640. return this.copyFromFloats(r, g, b);
  1641. };
  1642. /**
  1643. * Compute the Color3 hexadecimal code as a string
  1644. * @returns a string containing the hexadecimal representation of the Color3 object
  1645. */
  1646. Color3.prototype.toHexString = function () {
  1647. var intR = (this.r * 255) | 0;
  1648. var intG = (this.g * 255) | 0;
  1649. var intB = (this.b * 255) | 0;
  1650. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1651. };
  1652. /**
  1653. * Computes a new Color3 converted from the current one to linear space
  1654. * @returns a new Color3 object
  1655. */
  1656. Color3.prototype.toLinearSpace = function () {
  1657. var convertedColor = new Color3();
  1658. this.toLinearSpaceToRef(convertedColor);
  1659. return convertedColor;
  1660. };
  1661. /**
  1662. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1663. * @param convertedColor defines the Color3 object where to store the linear space version
  1664. * @returns the unmodified Color3
  1665. */
  1666. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1667. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1668. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1669. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1670. return this;
  1671. };
  1672. /**
  1673. * Computes a new Color3 converted from the current one to gamma space
  1674. * @returns a new Color3 object
  1675. */
  1676. Color3.prototype.toGammaSpace = function () {
  1677. var convertedColor = new Color3();
  1678. this.toGammaSpaceToRef(convertedColor);
  1679. return convertedColor;
  1680. };
  1681. /**
  1682. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1683. * @param convertedColor defines the Color3 object where to store the gamma space version
  1684. * @returns the unmodified Color3
  1685. */
  1686. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1687. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1688. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1689. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1690. return this;
  1691. };
  1692. // Statics
  1693. /**
  1694. * Creates a new Color3 from the string containing valid hexadecimal values
  1695. * @param hex defines a string containing valid hexadecimal values
  1696. * @returns a new Color3 object
  1697. */
  1698. Color3.FromHexString = function (hex) {
  1699. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1700. return new Color3(0, 0, 0);
  1701. }
  1702. var r = parseInt(hex.substring(1, 3), 16);
  1703. var g = parseInt(hex.substring(3, 5), 16);
  1704. var b = parseInt(hex.substring(5, 7), 16);
  1705. return Color3.FromInts(r, g, b);
  1706. };
  1707. /**
  1708. * Creates a new Vector3 from the starting index of the passed array
  1709. * @param array defines the source array
  1710. * @param offset defines an offset in the source array
  1711. * @returns a new Color3 object
  1712. */
  1713. Color3.FromArray = function (array, offset) {
  1714. if (offset === void 0) { offset = 0; }
  1715. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1716. };
  1717. /**
  1718. * Creates a new Color3 from integer values (< 256)
  1719. * @param r defines the red component to read from (value between 0 and 255)
  1720. * @param g defines the green component to read from (value between 0 and 255)
  1721. * @param b defines the blue component to read from (value between 0 and 255)
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.FromInts = function (r, g, b) {
  1725. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1726. };
  1727. /**
  1728. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1729. * @param start defines the start Color3 value
  1730. * @param end defines the end Color3 value
  1731. * @param amount defines the gradient value between start and end
  1732. * @returns a new Color3 object
  1733. */
  1734. Color3.Lerp = function (start, end, amount) {
  1735. var r = start.r + ((end.r - start.r) * amount);
  1736. var g = start.g + ((end.g - start.g) * amount);
  1737. var b = start.b + ((end.b - start.b) * amount);
  1738. return new Color3(r, g, b);
  1739. };
  1740. /**
  1741. * Returns a Color3 value containing a red color
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.Red = function () { return new Color3(1, 0, 0); };
  1745. /**
  1746. * Returns a Color3 value containing a green color
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.Green = function () { return new Color3(0, 1, 0); };
  1750. /**
  1751. * Returns a Color3 value containing a blue color
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1755. /**
  1756. * Returns a Color3 value containing a black color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Black = function () { return new Color3(0, 0, 0); };
  1760. /**
  1761. * Returns a Color3 value containing a white color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.White = function () { return new Color3(1, 1, 1); };
  1765. /**
  1766. * Returns a Color3 value containing a purple color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1770. /**
  1771. * Returns a Color3 value containing a magenta color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1775. /**
  1776. * Returns a Color3 value containing a yellow color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1780. /**
  1781. * Returns a Color3 value containing a gray color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1785. /**
  1786. * Returns a Color3 value containing a teal color
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1790. /**
  1791. * Returns a Color3 value containing a random color
  1792. * @returns a new Color3 object
  1793. */
  1794. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1795. return Color3;
  1796. }());
  1797. BABYLON.Color3 = Color3;
  1798. /**
  1799. * Class used to hold a RBGA color
  1800. */
  1801. var Color4 = /** @class */ (function () {
  1802. /**
  1803. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1804. * @param r defines the red component (between 0 and 1, default is 0)
  1805. * @param g defines the green component (between 0 and 1, default is 0)
  1806. * @param b defines the blue component (between 0 and 1, default is 0)
  1807. * @param a defines the alpha component (between 0 and 1, default is 1)
  1808. */
  1809. function Color4(
  1810. /**
  1811. * Defines the red component (between 0 and 1, default is 0)
  1812. */
  1813. r,
  1814. /**
  1815. * Defines the green component (between 0 and 1, default is 0)
  1816. */
  1817. g,
  1818. /**
  1819. * Defines the blue component (between 0 and 1, default is 0)
  1820. */
  1821. b,
  1822. /**
  1823. * Defines the alpha component (between 0 and 1, default is 1)
  1824. */
  1825. a) {
  1826. if (r === void 0) { r = 0; }
  1827. if (g === void 0) { g = 0; }
  1828. if (b === void 0) { b = 0; }
  1829. if (a === void 0) { a = 1; }
  1830. this.r = r;
  1831. this.g = g;
  1832. this.b = b;
  1833. this.a = a;
  1834. }
  1835. // Operators
  1836. /**
  1837. * Adds in place the passed Color4 values to the current Color4 object
  1838. * @param right defines the second operand
  1839. * @returns the current updated Color4 object
  1840. */
  1841. Color4.prototype.addInPlace = function (right) {
  1842. this.r += right.r;
  1843. this.g += right.g;
  1844. this.b += right.b;
  1845. this.a += right.a;
  1846. return this;
  1847. };
  1848. /**
  1849. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1850. * @returns the new array
  1851. */
  1852. Color4.prototype.asArray = function () {
  1853. var result = new Array();
  1854. this.toArray(result, 0);
  1855. return result;
  1856. };
  1857. /**
  1858. * Stores from the starting index in the passed array the Color4 successive values
  1859. * @param array defines the array where to store the r,g,b components
  1860. * @param index defines an optional index in the target array to define where to start storing values
  1861. * @returns the current Color4 object
  1862. */
  1863. Color4.prototype.toArray = function (array, index) {
  1864. if (index === undefined) {
  1865. index = 0;
  1866. }
  1867. array[index] = this.r;
  1868. array[index + 1] = this.g;
  1869. array[index + 2] = this.b;
  1870. array[index + 3] = this.a;
  1871. return this;
  1872. };
  1873. /**
  1874. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1875. * @param right defines the second operand
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.add = function (right) {
  1879. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1880. };
  1881. /**
  1882. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1883. * @param right defines the second operand
  1884. * @returns a new Color4 object
  1885. */
  1886. Color4.prototype.subtract = function (right) {
  1887. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1888. };
  1889. /**
  1890. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1891. * @param right defines the second operand
  1892. * @param result defines the Color4 object where to store the result
  1893. * @returns the current Color4 object
  1894. */
  1895. Color4.prototype.subtractToRef = function (right, result) {
  1896. result.r = this.r - right.r;
  1897. result.g = this.g - right.g;
  1898. result.b = this.b - right.b;
  1899. result.a = this.a - right.a;
  1900. return this;
  1901. };
  1902. /**
  1903. * Creates a new Color4 with the current Color4 values multiplied by scale
  1904. * @param scale defines the scaling factor to apply
  1905. * @returns a new Color4 object
  1906. */
  1907. Color4.prototype.scale = function (scale) {
  1908. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1909. };
  1910. /**
  1911. * Multiplies the current Color4 values by scale and stores the result in "result"
  1912. * @param scale defines the scaling factor to apply
  1913. * @param result defines the Color4 object where to store the result
  1914. * @returns the current Color4.
  1915. */
  1916. Color4.prototype.scaleToRef = function (scale, result) {
  1917. result.r = this.r * scale;
  1918. result.g = this.g * scale;
  1919. result.b = this.b * scale;
  1920. result.a = this.a * scale;
  1921. return this;
  1922. };
  1923. /**
  1924. * Clamps the rgb values by the min and max values and stores the result into "result"
  1925. * @param min defines minimum clamping value (default is 0)
  1926. * @param max defines maximum clamping value (default is 1)
  1927. * @param result defines color to store the result into.
  1928. * @returns the cuurent Color4
  1929. */
  1930. Color4.prototype.clampToRef = function (min, max, result) {
  1931. if (min === void 0) { min = 0; }
  1932. if (max === void 0) { max = 1; }
  1933. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1934. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1935. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1936. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1937. return this;
  1938. };
  1939. /**
  1940. * Multipy an Color4 value by another and return a new Color4 object
  1941. * @param color defines the Color4 value to multiply by
  1942. * @returns a new Color4 object
  1943. */
  1944. Color4.prototype.multiply = function (color) {
  1945. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1946. };
  1947. /**
  1948. * Multipy a Color4 value by another and push the result in a reference value
  1949. * @param color defines the Color4 value to multiply by
  1950. * @param result defines the Color4 to fill the result in
  1951. * @returns the result Color4
  1952. */
  1953. Color4.prototype.multiplyToRef = function (color, result) {
  1954. result.r = this.r * color.r;
  1955. result.g = this.g * color.g;
  1956. result.b = this.b * color.b;
  1957. result.a = this.a * color.a;
  1958. return result;
  1959. };
  1960. /**
  1961. * Creates a string with the Color4 current values
  1962. * @returns the string representation of the Color4 object
  1963. */
  1964. Color4.prototype.toString = function () {
  1965. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1966. };
  1967. /**
  1968. * Returns the string "Color4"
  1969. * @returns "Color4"
  1970. */
  1971. Color4.prototype.getClassName = function () {
  1972. return "Color4";
  1973. };
  1974. /**
  1975. * Compute the Color4 hash code
  1976. * @returns an unique number that can be used to hash Color4 objects
  1977. */
  1978. Color4.prototype.getHashCode = function () {
  1979. var hash = this.r || 0;
  1980. hash = (hash * 397) ^ (this.g || 0);
  1981. hash = (hash * 397) ^ (this.b || 0);
  1982. hash = (hash * 397) ^ (this.a || 0);
  1983. return hash;
  1984. };
  1985. /**
  1986. * Creates a new Color4 copied from the current one
  1987. * @returns a new Color4 object
  1988. */
  1989. Color4.prototype.clone = function () {
  1990. return new Color4(this.r, this.g, this.b, this.a);
  1991. };
  1992. /**
  1993. * Copies the passed Color4 values into the current one
  1994. * @param source defines the source Color4 object
  1995. * @returns the current updated Color4 object
  1996. */
  1997. Color4.prototype.copyFrom = function (source) {
  1998. this.r = source.r;
  1999. this.g = source.g;
  2000. this.b = source.b;
  2001. this.a = source.a;
  2002. return this;
  2003. };
  2004. /**
  2005. * Copies the passed float values into the current one
  2006. * @param r defines the red component to read from
  2007. * @param g defines the green component to read from
  2008. * @param b defines the blue component to read from
  2009. * @param a defines the alpha component to read from
  2010. * @returns the current updated Color4 object
  2011. */
  2012. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2013. this.r = r;
  2014. this.g = g;
  2015. this.b = b;
  2016. this.a = a;
  2017. return this;
  2018. };
  2019. /**
  2020. * Copies the passed float values into the current one
  2021. * @param r defines the red component to read from
  2022. * @param g defines the green component to read from
  2023. * @param b defines the blue component to read from
  2024. * @param a defines the alpha component to read from
  2025. * @returns the current updated Color4 object
  2026. */
  2027. Color4.prototype.set = function (r, g, b, a) {
  2028. return this.copyFromFloats(r, g, b, a);
  2029. };
  2030. /**
  2031. * Compute the Color4 hexadecimal code as a string
  2032. * @returns a string containing the hexadecimal representation of the Color4 object
  2033. */
  2034. Color4.prototype.toHexString = function () {
  2035. var intR = (this.r * 255) | 0;
  2036. var intG = (this.g * 255) | 0;
  2037. var intB = (this.b * 255) | 0;
  2038. var intA = (this.a * 255) | 0;
  2039. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2040. };
  2041. /**
  2042. * Computes a new Color4 converted from the current one to linear space
  2043. * @returns a new Color4 object
  2044. */
  2045. Color4.prototype.toLinearSpace = function () {
  2046. var convertedColor = new Color4();
  2047. this.toLinearSpaceToRef(convertedColor);
  2048. return convertedColor;
  2049. };
  2050. /**
  2051. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2052. * @param convertedColor defines the Color4 object where to store the linear space version
  2053. * @returns the unmodified Color4
  2054. */
  2055. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2056. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2057. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2058. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2059. convertedColor.a = this.a;
  2060. return this;
  2061. };
  2062. /**
  2063. * Computes a new Color4 converted from the current one to gamma space
  2064. * @returns a new Color4 object
  2065. */
  2066. Color4.prototype.toGammaSpace = function () {
  2067. var convertedColor = new Color4();
  2068. this.toGammaSpaceToRef(convertedColor);
  2069. return convertedColor;
  2070. };
  2071. /**
  2072. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2073. * @param convertedColor defines the Color4 object where to store the gamma space version
  2074. * @returns the unmodified Color4
  2075. */
  2076. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2077. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2078. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2079. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2080. convertedColor.a = this.a;
  2081. return this;
  2082. };
  2083. // Statics
  2084. /**
  2085. * Creates a new Color4 from the string containing valid hexadecimal values
  2086. * @param hex defines a string containing valid hexadecimal values
  2087. * @returns a new Color4 object
  2088. */
  2089. Color4.FromHexString = function (hex) {
  2090. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2091. return new Color4(0.0, 0.0, 0.0, 0.0);
  2092. }
  2093. var r = parseInt(hex.substring(1, 3), 16);
  2094. var g = parseInt(hex.substring(3, 5), 16);
  2095. var b = parseInt(hex.substring(5, 7), 16);
  2096. var a = parseInt(hex.substring(7, 9), 16);
  2097. return Color4.FromInts(r, g, b, a);
  2098. };
  2099. /**
  2100. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2101. * @param left defines the start value
  2102. * @param right defines the end value
  2103. * @param amount defines the gradient factor
  2104. * @returns a new Color4 object
  2105. */
  2106. Color4.Lerp = function (left, right, amount) {
  2107. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2108. Color4.LerpToRef(left, right, amount, result);
  2109. return result;
  2110. };
  2111. /**
  2112. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2113. * @param left defines the start value
  2114. * @param right defines the end value
  2115. * @param amount defines the gradient factor
  2116. * @param result defines the Color4 object where to store data
  2117. */
  2118. Color4.LerpToRef = function (left, right, amount, result) {
  2119. result.r = left.r + (right.r - left.r) * amount;
  2120. result.g = left.g + (right.g - left.g) * amount;
  2121. result.b = left.b + (right.b - left.b) * amount;
  2122. result.a = left.a + (right.a - left.a) * amount;
  2123. };
  2124. /**
  2125. * Creates a new Color4 from the starting index element of the passed array
  2126. * @param array defines the source array to read from
  2127. * @param offset defines the offset in the source array
  2128. * @returns a new Color4 object
  2129. */
  2130. Color4.FromArray = function (array, offset) {
  2131. if (offset === void 0) { offset = 0; }
  2132. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2133. };
  2134. /**
  2135. * Creates a new Color3 from integer values (< 256)
  2136. * @param r defines the red component to read from (value between 0 and 255)
  2137. * @param g defines the green component to read from (value between 0 and 255)
  2138. * @param b defines the blue component to read from (value between 0 and 255)
  2139. * @param a defines the alpha component to read from (value between 0 and 255)
  2140. * @returns a new Color3 object
  2141. */
  2142. Color4.FromInts = function (r, g, b, a) {
  2143. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2144. };
  2145. /**
  2146. * Check the content of a given array and convert it to an array containing RGBA data
  2147. * If the original array was already containing count * 4 values then it is returned directly
  2148. * @param colors defines the array to check
  2149. * @param count defines the number of RGBA data to expect
  2150. * @returns an array containing count * 4 values (RGBA)
  2151. */
  2152. Color4.CheckColors4 = function (colors, count) {
  2153. // Check if color3 was used
  2154. if (colors.length === count * 3) {
  2155. var colors4 = [];
  2156. for (var index = 0; index < colors.length; index += 3) {
  2157. var newIndex = (index / 3) * 4;
  2158. colors4[newIndex] = colors[index];
  2159. colors4[newIndex + 1] = colors[index + 1];
  2160. colors4[newIndex + 2] = colors[index + 2];
  2161. colors4[newIndex + 3] = 1.0;
  2162. }
  2163. return colors4;
  2164. }
  2165. return colors;
  2166. };
  2167. return Color4;
  2168. }());
  2169. BABYLON.Color4 = Color4;
  2170. var Vector2 = /** @class */ (function () {
  2171. /**
  2172. * Creates a new Vector2 from the passed x and y coordinates.
  2173. */
  2174. function Vector2(x, y) {
  2175. this.x = x;
  2176. this.y = y;
  2177. }
  2178. /**
  2179. * Returns a string with the Vector2 coordinates.
  2180. */
  2181. Vector2.prototype.toString = function () {
  2182. return "{X: " + this.x + " Y:" + this.y + "}";
  2183. };
  2184. /**
  2185. * Returns the string "Vector2"
  2186. */
  2187. Vector2.prototype.getClassName = function () {
  2188. return "Vector2";
  2189. };
  2190. /**
  2191. * Returns the Vector2 hash code as a number.
  2192. */
  2193. Vector2.prototype.getHashCode = function () {
  2194. var hash = this.x || 0;
  2195. hash = (hash * 397) ^ (this.y || 0);
  2196. return hash;
  2197. };
  2198. // Operators
  2199. /**
  2200. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2201. * Returns the Vector2.
  2202. */
  2203. Vector2.prototype.toArray = function (array, index) {
  2204. if (index === void 0) { index = 0; }
  2205. array[index] = this.x;
  2206. array[index + 1] = this.y;
  2207. return this;
  2208. };
  2209. /**
  2210. * Returns a new array with 2 elements : the Vector2 coordinates.
  2211. */
  2212. Vector2.prototype.asArray = function () {
  2213. var result = new Array();
  2214. this.toArray(result, 0);
  2215. return result;
  2216. };
  2217. /**
  2218. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2219. * Returns the updated Vector2.
  2220. */
  2221. Vector2.prototype.copyFrom = function (source) {
  2222. this.x = source.x;
  2223. this.y = source.y;
  2224. return this;
  2225. };
  2226. /**
  2227. * Sets the Vector2 coordinates with the passed floats.
  2228. * Returns the updated Vector2.
  2229. */
  2230. Vector2.prototype.copyFromFloats = function (x, y) {
  2231. this.x = x;
  2232. this.y = y;
  2233. return this;
  2234. };
  2235. /**
  2236. * Sets the Vector2 coordinates with the passed floats.
  2237. * Returns the updated Vector2.
  2238. */
  2239. Vector2.prototype.set = function (x, y) {
  2240. return this.copyFromFloats(x, y);
  2241. };
  2242. /**
  2243. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2244. */
  2245. Vector2.prototype.add = function (otherVector) {
  2246. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2247. };
  2248. /**
  2249. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2250. * Returns the Vector2.
  2251. */
  2252. Vector2.prototype.addToRef = function (otherVector, result) {
  2253. result.x = this.x + otherVector.x;
  2254. result.y = this.y + otherVector.y;
  2255. return this;
  2256. };
  2257. /**
  2258. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2259. * Returns the updated Vector2.
  2260. */
  2261. Vector2.prototype.addInPlace = function (otherVector) {
  2262. this.x += otherVector.x;
  2263. this.y += otherVector.y;
  2264. return this;
  2265. };
  2266. /**
  2267. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2268. */
  2269. Vector2.prototype.addVector3 = function (otherVector) {
  2270. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2271. };
  2272. /**
  2273. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2274. */
  2275. Vector2.prototype.subtract = function (otherVector) {
  2276. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2277. };
  2278. /**
  2279. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2280. * Returns the Vector2.
  2281. */
  2282. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2283. result.x = this.x - otherVector.x;
  2284. result.y = this.y - otherVector.y;
  2285. return this;
  2286. };
  2287. /**
  2288. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2289. * Returns the updated Vector2.
  2290. */
  2291. Vector2.prototype.subtractInPlace = function (otherVector) {
  2292. this.x -= otherVector.x;
  2293. this.y -= otherVector.y;
  2294. return this;
  2295. };
  2296. /**
  2297. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2298. * Returns the updated Vector2.
  2299. */
  2300. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2301. this.x *= otherVector.x;
  2302. this.y *= otherVector.y;
  2303. return this;
  2304. };
  2305. /**
  2306. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2307. */
  2308. Vector2.prototype.multiply = function (otherVector) {
  2309. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2310. };
  2311. /**
  2312. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2313. * Returns the Vector2.
  2314. */
  2315. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2316. result.x = this.x * otherVector.x;
  2317. result.y = this.y * otherVector.y;
  2318. return this;
  2319. };
  2320. /**
  2321. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2322. */
  2323. Vector2.prototype.multiplyByFloats = function (x, y) {
  2324. return new Vector2(this.x * x, this.y * y);
  2325. };
  2326. /**
  2327. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2328. */
  2329. Vector2.prototype.divide = function (otherVector) {
  2330. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2331. };
  2332. /**
  2333. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2334. * Returns the Vector2.
  2335. */
  2336. Vector2.prototype.divideToRef = function (otherVector, result) {
  2337. result.x = this.x / otherVector.x;
  2338. result.y = this.y / otherVector.y;
  2339. return this;
  2340. };
  2341. /**
  2342. * Divides the current Vector3 coordinates by the passed ones.
  2343. * Returns the updated Vector3.
  2344. */
  2345. Vector2.prototype.divideInPlace = function (otherVector) {
  2346. return this.divideToRef(otherVector, this);
  2347. };
  2348. /**
  2349. * Returns a new Vector2 with current Vector2 negated coordinates.
  2350. */
  2351. Vector2.prototype.negate = function () {
  2352. return new Vector2(-this.x, -this.y);
  2353. };
  2354. /**
  2355. * Multiply the Vector2 coordinates by scale.
  2356. * Returns the updated Vector2.
  2357. */
  2358. Vector2.prototype.scaleInPlace = function (scale) {
  2359. this.x *= scale;
  2360. this.y *= scale;
  2361. return this;
  2362. };
  2363. /**
  2364. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2365. */
  2366. Vector2.prototype.scale = function (scale) {
  2367. return new Vector2(this.x * scale, this.y * scale);
  2368. };
  2369. /**
  2370. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2371. */
  2372. Vector2.prototype.equals = function (otherVector) {
  2373. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2374. };
  2375. /**
  2376. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2377. */
  2378. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2379. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2380. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2381. };
  2382. // Properties
  2383. /**
  2384. * Returns the vector length (float).
  2385. */
  2386. Vector2.prototype.length = function () {
  2387. return Math.sqrt(this.x * this.x + this.y * this.y);
  2388. };
  2389. /**
  2390. * Returns the vector squared length (float);
  2391. */
  2392. Vector2.prototype.lengthSquared = function () {
  2393. return (this.x * this.x + this.y * this.y);
  2394. };
  2395. // Methods
  2396. /**
  2397. * Normalize the vector.
  2398. * Returns the updated Vector2.
  2399. */
  2400. Vector2.prototype.normalize = function () {
  2401. var len = this.length();
  2402. if (len === 0)
  2403. return this;
  2404. var num = 1.0 / len;
  2405. this.x *= num;
  2406. this.y *= num;
  2407. return this;
  2408. };
  2409. /**
  2410. * Returns a new Vector2 copied from the Vector2.
  2411. */
  2412. Vector2.prototype.clone = function () {
  2413. return new Vector2(this.x, this.y);
  2414. };
  2415. // Statics
  2416. /**
  2417. * Returns a new Vector2(0, 0)
  2418. */
  2419. Vector2.Zero = function () {
  2420. return new Vector2(0, 0);
  2421. };
  2422. /**
  2423. * Returns a new Vector2(1, 1)
  2424. */
  2425. Vector2.One = function () {
  2426. return new Vector2(1, 1);
  2427. };
  2428. /**
  2429. * Returns a new Vector2 set from the passed index element of the passed array.
  2430. */
  2431. Vector2.FromArray = function (array, offset) {
  2432. if (offset === void 0) { offset = 0; }
  2433. return new Vector2(array[offset], array[offset + 1]);
  2434. };
  2435. /**
  2436. * Sets "result" from the passed index element of the passed array.
  2437. */
  2438. Vector2.FromArrayToRef = function (array, offset, result) {
  2439. result.x = array[offset];
  2440. result.y = array[offset + 1];
  2441. };
  2442. /**
  2443. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2444. */
  2445. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2446. var squared = amount * amount;
  2447. var cubed = amount * squared;
  2448. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2449. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2450. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2451. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2452. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2453. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2454. return new Vector2(x, y);
  2455. };
  2456. /**
  2457. * 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".
  2458. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2459. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2460. */
  2461. Vector2.Clamp = function (value, min, max) {
  2462. var x = value.x;
  2463. x = (x > max.x) ? max.x : x;
  2464. x = (x < min.x) ? min.x : x;
  2465. var y = value.y;
  2466. y = (y > max.y) ? max.y : y;
  2467. y = (y < min.y) ? min.y : y;
  2468. return new Vector2(x, y);
  2469. };
  2470. /**
  2471. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2472. */
  2473. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2474. var squared = amount * amount;
  2475. var cubed = amount * squared;
  2476. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2477. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2478. var part3 = (cubed - (2.0 * squared)) + amount;
  2479. var part4 = cubed - squared;
  2480. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2481. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2482. return new Vector2(x, y);
  2483. };
  2484. /**
  2485. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2486. */
  2487. Vector2.Lerp = function (start, end, amount) {
  2488. var x = start.x + ((end.x - start.x) * amount);
  2489. var y = start.y + ((end.y - start.y) * amount);
  2490. return new Vector2(x, y);
  2491. };
  2492. /**
  2493. * Returns the dot product (float) of the vector "left" and the vector "right".
  2494. */
  2495. Vector2.Dot = function (left, right) {
  2496. return left.x * right.x + left.y * right.y;
  2497. };
  2498. /**
  2499. * Returns a new Vector2 equal to the normalized passed vector.
  2500. */
  2501. Vector2.Normalize = function (vector) {
  2502. var newVector = vector.clone();
  2503. newVector.normalize();
  2504. return newVector;
  2505. };
  2506. /**
  2507. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2508. */
  2509. Vector2.Minimize = function (left, right) {
  2510. var x = (left.x < right.x) ? left.x : right.x;
  2511. var y = (left.y < right.y) ? left.y : right.y;
  2512. return new Vector2(x, y);
  2513. };
  2514. /**
  2515. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2516. */
  2517. Vector2.Maximize = function (left, right) {
  2518. var x = (left.x > right.x) ? left.x : right.x;
  2519. var y = (left.y > right.y) ? left.y : right.y;
  2520. return new Vector2(x, y);
  2521. };
  2522. /**
  2523. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2524. */
  2525. Vector2.Transform = function (vector, transformation) {
  2526. var r = Vector2.Zero();
  2527. Vector2.TransformToRef(vector, transformation, r);
  2528. return r;
  2529. };
  2530. /**
  2531. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2532. */
  2533. Vector2.TransformToRef = function (vector, transformation, result) {
  2534. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2535. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2536. result.x = x;
  2537. result.y = y;
  2538. };
  2539. /**
  2540. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2541. */
  2542. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2543. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2544. var sign = a < 0 ? -1 : 1;
  2545. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2546. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2547. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2548. };
  2549. /**
  2550. * Returns the distance (float) between the vectors "value1" and "value2".
  2551. */
  2552. Vector2.Distance = function (value1, value2) {
  2553. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2554. };
  2555. /**
  2556. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2557. */
  2558. Vector2.DistanceSquared = function (value1, value2) {
  2559. var x = value1.x - value2.x;
  2560. var y = value1.y - value2.y;
  2561. return (x * x) + (y * y);
  2562. };
  2563. /**
  2564. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2565. */
  2566. Vector2.Center = function (value1, value2) {
  2567. var center = value1.add(value2);
  2568. center.scaleInPlace(0.5);
  2569. return center;
  2570. };
  2571. /**
  2572. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2573. */
  2574. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2575. var l2 = Vector2.DistanceSquared(segA, segB);
  2576. if (l2 === 0.0) {
  2577. return Vector2.Distance(p, segA);
  2578. }
  2579. var v = segB.subtract(segA);
  2580. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2581. var proj = segA.add(v.multiplyByFloats(t, t));
  2582. return Vector2.Distance(p, proj);
  2583. };
  2584. return Vector2;
  2585. }());
  2586. BABYLON.Vector2 = Vector2;
  2587. /**
  2588. * Classed used to store (x,y,z) vector representation
  2589. * A Vector3 is the main object used in 3D geometry
  2590. * It can represent etiher the coordinates of a point the space, either a direction
  2591. * Reminder: Babylon.js uses a left handed forward facing system
  2592. */
  2593. var Vector3 = /** @class */ (function () {
  2594. /**
  2595. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2596. * @param x defines the first coordinates (on X axis)
  2597. * @param y defines the second coordinates (on Y axis)
  2598. * @param z defines the third coordinates (on Z axis)
  2599. */
  2600. function Vector3(
  2601. /**
  2602. * Defines the first coordinates (on X axis)
  2603. */
  2604. x,
  2605. /**
  2606. * Defines the second coordinates (on Y axis)
  2607. */
  2608. y,
  2609. /**
  2610. * Defines the third coordinates (on Z axis)
  2611. */
  2612. z) {
  2613. this.x = x;
  2614. this.y = y;
  2615. this.z = z;
  2616. }
  2617. /**
  2618. * Creates a string representation of the Vector3
  2619. * @returns a string with the Vector3 coordinates.
  2620. */
  2621. Vector3.prototype.toString = function () {
  2622. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2623. };
  2624. /**
  2625. * Gets the class name
  2626. * @returns the string "Vector3"
  2627. */
  2628. Vector3.prototype.getClassName = function () {
  2629. return "Vector3";
  2630. };
  2631. /**
  2632. * Creates the Vector3 hash code
  2633. * @returns a number which tends to be unique between Vector3 instances
  2634. */
  2635. Vector3.prototype.getHashCode = function () {
  2636. var hash = this.x || 0;
  2637. hash = (hash * 397) ^ (this.y || 0);
  2638. hash = (hash * 397) ^ (this.z || 0);
  2639. return hash;
  2640. };
  2641. // Operators
  2642. /**
  2643. * Creates an array containing three elements : the coordinates of the Vector3
  2644. * @returns a new array of numbers
  2645. */
  2646. Vector3.prototype.asArray = function () {
  2647. var result = [];
  2648. this.toArray(result, 0);
  2649. return result;
  2650. };
  2651. /**
  2652. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2653. * @param array defines the destination array
  2654. * @param index defines the offset in the destination array
  2655. * @returns the current Vector3
  2656. */
  2657. Vector3.prototype.toArray = function (array, index) {
  2658. if (index === void 0) { index = 0; }
  2659. array[index] = this.x;
  2660. array[index + 1] = this.y;
  2661. array[index + 2] = this.z;
  2662. return this;
  2663. };
  2664. /**
  2665. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2666. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2667. */
  2668. Vector3.prototype.toQuaternion = function () {
  2669. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2670. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2671. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2672. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2673. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2674. var cosy = Math.cos(this.y * 0.5);
  2675. var siny = Math.sin(this.y * 0.5);
  2676. result.x = coszMinusx * siny;
  2677. result.y = -sinzMinusx * siny;
  2678. result.z = sinxPlusz * cosy;
  2679. result.w = cosxPlusz * cosy;
  2680. return result;
  2681. };
  2682. /**
  2683. * Adds the passed vector to the current Vector3
  2684. * @param otherVector defines the second operand
  2685. * @returns the current updated Vector3
  2686. */
  2687. Vector3.prototype.addInPlace = function (otherVector) {
  2688. this.x += otherVector.x;
  2689. this.y += otherVector.y;
  2690. this.z += otherVector.z;
  2691. return this;
  2692. };
  2693. /**
  2694. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2695. * @param otherVector defines the second operand
  2696. * @returns the resulting Vector3
  2697. */
  2698. Vector3.prototype.add = function (otherVector) {
  2699. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2700. };
  2701. /**
  2702. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2703. * @param otherVector defines the second operand
  2704. * @param result defines the Vector3 object where to store the result
  2705. * @returns the current Vector3
  2706. */
  2707. Vector3.prototype.addToRef = function (otherVector, result) {
  2708. result.x = this.x + otherVector.x;
  2709. result.y = this.y + otherVector.y;
  2710. result.z = this.z + otherVector.z;
  2711. return this;
  2712. };
  2713. /**
  2714. * Subtract the passed vector from the current Vector3
  2715. * @param otherVector defines the second operand
  2716. * @returns the current updated Vector3
  2717. */
  2718. Vector3.prototype.subtractInPlace = function (otherVector) {
  2719. this.x -= otherVector.x;
  2720. this.y -= otherVector.y;
  2721. this.z -= otherVector.z;
  2722. return this;
  2723. };
  2724. /**
  2725. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2726. * @param otherVector defines the second operand
  2727. * @returns the resulting Vector3
  2728. */
  2729. Vector3.prototype.subtract = function (otherVector) {
  2730. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2731. };
  2732. /**
  2733. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2734. * @param otherVector defines the second operand
  2735. * @param result defines the Vector3 object where to store the result
  2736. * @returns the current Vector3
  2737. */
  2738. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2739. result.x = this.x - otherVector.x;
  2740. result.y = this.y - otherVector.y;
  2741. result.z = this.z - otherVector.z;
  2742. return this;
  2743. };
  2744. /**
  2745. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2746. * @param x defines the x coordinate of the operand
  2747. * @param y defines the y coordinate of the operand
  2748. * @param z defines the z coordinate of the operand
  2749. * @returns the resulting Vector3
  2750. */
  2751. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2752. return new Vector3(this.x - x, this.y - y, this.z - z);
  2753. };
  2754. /**
  2755. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2756. * @param x defines the x coordinate of the operand
  2757. * @param y defines the y coordinate of the operand
  2758. * @param z defines the z coordinate of the operand
  2759. * @param result defines the Vector3 object where to store the result
  2760. * @returns the current Vector3
  2761. */
  2762. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2763. result.x = this.x - x;
  2764. result.y = this.y - y;
  2765. result.z = this.z - z;
  2766. return this;
  2767. };
  2768. /**
  2769. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2770. * @returns a new Vector3
  2771. */
  2772. Vector3.prototype.negate = function () {
  2773. return new Vector3(-this.x, -this.y, -this.z);
  2774. };
  2775. /**
  2776. * Multiplies the Vector3 coordinates by the float "scale"
  2777. * @param scale defines the multiplier factor
  2778. * @returns the current updated Vector3
  2779. */
  2780. Vector3.prototype.scaleInPlace = function (scale) {
  2781. this.x *= scale;
  2782. this.y *= scale;
  2783. this.z *= scale;
  2784. return this;
  2785. };
  2786. /**
  2787. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2788. * @param scale defines the multiplier factor
  2789. * @returns a new Vector3
  2790. */
  2791. Vector3.prototype.scale = function (scale) {
  2792. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2793. };
  2794. /**
  2795. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2796. * @param scale defines the multiplier factor
  2797. * @param result defines the Vector3 object where to store the result
  2798. * @returns the current Vector3
  2799. */
  2800. Vector3.prototype.scaleToRef = function (scale, result) {
  2801. result.x = this.x * scale;
  2802. result.y = this.y * scale;
  2803. result.z = this.z * scale;
  2804. return this;
  2805. };
  2806. /**
  2807. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2808. * @param otherVector defines the second operand
  2809. * @returns true if both vectors are equals
  2810. */
  2811. Vector3.prototype.equals = function (otherVector) {
  2812. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2813. };
  2814. /**
  2815. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2816. * @param otherVector defines the second operand
  2817. * @param epsilon defines the minimal distance to define values as equals
  2818. * @returns true if both vectors are distant less than epsilon
  2819. */
  2820. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2821. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2822. 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);
  2823. };
  2824. /**
  2825. * Returns true if the current Vector3 coordinates equals the passed floats
  2826. * @param x defines the x coordinate of the operand
  2827. * @param y defines the y coordinate of the operand
  2828. * @param z defines the z coordinate of the operand
  2829. * @returns true if both vectors are equals
  2830. */
  2831. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2832. return this.x === x && this.y === y && this.z === z;
  2833. };
  2834. /**
  2835. * Multiplies the current Vector3 coordinates by the passed ones
  2836. * @param otherVector defines the second operand
  2837. * @returns the current updated Vector3
  2838. */
  2839. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2840. this.x *= otherVector.x;
  2841. this.y *= otherVector.y;
  2842. this.z *= otherVector.z;
  2843. return this;
  2844. };
  2845. /**
  2846. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2847. * @param otherVector defines the second operand
  2848. * @returns the new Vector3
  2849. */
  2850. Vector3.prototype.multiply = function (otherVector) {
  2851. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2852. };
  2853. /**
  2854. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2855. * @param otherVector defines the second operand
  2856. * @param result defines the Vector3 object where to store the result
  2857. * @returns the current Vector3
  2858. */
  2859. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2860. result.x = this.x * otherVector.x;
  2861. result.y = this.y * otherVector.y;
  2862. result.z = this.z * otherVector.z;
  2863. return this;
  2864. };
  2865. /**
  2866. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2867. * @param x defines the x coordinate of the operand
  2868. * @param y defines the y coordinate of the operand
  2869. * @param z defines the z coordinate of the operand
  2870. * @returns the new Vector3
  2871. */
  2872. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2873. return new Vector3(this.x * x, this.y * y, this.z * z);
  2874. };
  2875. /**
  2876. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2877. * @param otherVector defines the second operand
  2878. * @returns the new Vector3
  2879. */
  2880. Vector3.prototype.divide = function (otherVector) {
  2881. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2882. };
  2883. /**
  2884. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2885. * @param otherVector defines the second operand
  2886. * @param result defines the Vector3 object where to store the result
  2887. * @returns the current Vector3
  2888. */
  2889. Vector3.prototype.divideToRef = function (otherVector, result) {
  2890. result.x = this.x / otherVector.x;
  2891. result.y = this.y / otherVector.y;
  2892. result.z = this.z / otherVector.z;
  2893. return this;
  2894. };
  2895. /**
  2896. * Divides the current Vector3 coordinates by the passed ones.
  2897. * @param otherVector defines the second operand
  2898. * @returns the current updated Vector3
  2899. */
  2900. Vector3.prototype.divideInPlace = function (otherVector) {
  2901. return this.divideToRef(otherVector, this);
  2902. };
  2903. /**
  2904. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2905. * @param other defines the second operand
  2906. * @returns the current updated Vector3
  2907. */
  2908. Vector3.prototype.minimizeInPlace = function (other) {
  2909. if (other.x < this.x)
  2910. this.x = other.x;
  2911. if (other.y < this.y)
  2912. this.y = other.y;
  2913. if (other.z < this.z)
  2914. this.z = other.z;
  2915. return this;
  2916. };
  2917. /**
  2918. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2919. * @param other defines the second operand
  2920. * @returns the current updated Vector3
  2921. */
  2922. Vector3.prototype.maximizeInPlace = function (other) {
  2923. if (other.x > this.x)
  2924. this.x = other.x;
  2925. if (other.y > this.y)
  2926. this.y = other.y;
  2927. if (other.z > this.z)
  2928. this.z = other.z;
  2929. return this;
  2930. };
  2931. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2932. /**
  2933. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2934. */
  2935. get: function () {
  2936. var absX = Math.abs(this.x);
  2937. var absY = Math.abs(this.y);
  2938. if (absX !== absY) {
  2939. return true;
  2940. }
  2941. var absZ = Math.abs(this.z);
  2942. if (absX !== absZ) {
  2943. return true;
  2944. }
  2945. if (absY !== absZ) {
  2946. return true;
  2947. }
  2948. return false;
  2949. },
  2950. enumerable: true,
  2951. configurable: true
  2952. });
  2953. // Properties
  2954. /**
  2955. * Gets the length of the Vector3
  2956. * @returns the length of the Vecto3
  2957. */
  2958. Vector3.prototype.length = function () {
  2959. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2960. };
  2961. /**
  2962. * Gets the squared length of the Vector3
  2963. * @returns squared length of the Vector3
  2964. */
  2965. Vector3.prototype.lengthSquared = function () {
  2966. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2967. };
  2968. /**
  2969. * Normalize the current Vector3.
  2970. * Please note that this is an in place operation.
  2971. * @returns the current updated Vector3
  2972. */
  2973. Vector3.prototype.normalize = function () {
  2974. var len = this.length();
  2975. if (len === 0 || len === 1.0)
  2976. return this;
  2977. var num = 1.0 / len;
  2978. this.x *= num;
  2979. this.y *= num;
  2980. this.z *= num;
  2981. return this;
  2982. };
  2983. /**
  2984. * Normalize the current Vector3 to a new vector
  2985. * @returns the new Vector3
  2986. */
  2987. Vector3.prototype.normalizeToNew = function () {
  2988. var normalized = new Vector3(0, 0, 0);
  2989. this.normalizeToRef(normalized);
  2990. return normalized;
  2991. };
  2992. /**
  2993. * Normalize the current Vector3 to the reference
  2994. * @param reference define the Vector3 to update
  2995. * @returns the updated Vector3
  2996. */
  2997. Vector3.prototype.normalizeToRef = function (reference) {
  2998. var len = this.length();
  2999. if (len === 0 || len === 1.0) {
  3000. reference.set(this.x, this.y, this.z);
  3001. return reference;
  3002. }
  3003. var scale = 1.0 / len;
  3004. this.scaleToRef(scale, reference);
  3005. return reference;
  3006. };
  3007. /**
  3008. * Creates a new Vector3 copied from the current Vector3
  3009. * @returns the new Vector3
  3010. */
  3011. Vector3.prototype.clone = function () {
  3012. return new Vector3(this.x, this.y, this.z);
  3013. };
  3014. /**
  3015. * Copies the passed vector coordinates to the current Vector3 ones
  3016. * @param source defines the source Vector3
  3017. * @returns the current updated Vector3
  3018. */
  3019. Vector3.prototype.copyFrom = function (source) {
  3020. this.x = source.x;
  3021. this.y = source.y;
  3022. this.z = source.z;
  3023. return this;
  3024. };
  3025. /**
  3026. * Copies the passed floats to the current Vector3 coordinates
  3027. * @param x defines the x coordinate of the operand
  3028. * @param y defines the y coordinate of the operand
  3029. * @param z defines the z coordinate of the operand
  3030. * @returns the current updated Vector3
  3031. */
  3032. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3033. this.x = x;
  3034. this.y = y;
  3035. this.z = z;
  3036. return this;
  3037. };
  3038. /**
  3039. * Copies the passed floats to the current Vector3 coordinates
  3040. * @param x defines the x coordinate of the operand
  3041. * @param y defines the y coordinate of the operand
  3042. * @param z defines the z coordinate of the operand
  3043. * @returns the current updated Vector3
  3044. */
  3045. Vector3.prototype.set = function (x, y, z) {
  3046. return this.copyFromFloats(x, y, z);
  3047. };
  3048. // Statics
  3049. /**
  3050. * Get the clip factor between two vectors
  3051. * @param vector0 defines the first operand
  3052. * @param vector1 defines the second operand
  3053. * @param axis defines the axis to use
  3054. * @param size defines the size along the axis
  3055. * @returns the clip factor
  3056. */
  3057. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3058. var d0 = Vector3.Dot(vector0, axis) - size;
  3059. var d1 = Vector3.Dot(vector1, axis) - size;
  3060. var s = d0 / (d0 - d1);
  3061. return s;
  3062. };
  3063. /**
  3064. * Get angle between two vectors
  3065. * @param vector0 angle between vector0 and vector1
  3066. * @param vector1 angle between vector0 and vector1
  3067. * @param normal direction of the normal
  3068. * @return the angle between vector0 and vector1
  3069. */
  3070. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3071. var v0 = vector0.clone().normalize();
  3072. var v1 = vector1.clone().normalize();
  3073. var dot = Vector3.Dot(v0, v1);
  3074. var n = Vector3.Cross(v0, v1);
  3075. if (Vector3.Dot(n, normal) > 0) {
  3076. return Math.acos(dot);
  3077. }
  3078. return -Math.acos(dot);
  3079. };
  3080. /**
  3081. * Returns a new Vector3 set from the index "offset" of the passed array
  3082. * @param array defines the source array
  3083. * @param offset defines the offset in the source array
  3084. * @returns the new Vector3
  3085. */
  3086. Vector3.FromArray = function (array, offset) {
  3087. if (!offset) {
  3088. offset = 0;
  3089. }
  3090. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3091. };
  3092. /**
  3093. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3094. * This function is deprecated. Use FromArray instead
  3095. * @param array defines the source array
  3096. * @param offset defines the offset in the source array
  3097. * @returns the new Vector3
  3098. */
  3099. Vector3.FromFloatArray = function (array, offset) {
  3100. return Vector3.FromArray(array, offset);
  3101. };
  3102. /**
  3103. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3104. * @param array defines the source array
  3105. * @param offset defines the offset in the source array
  3106. * @param result defines the Vector3 where to store the result
  3107. */
  3108. Vector3.FromArrayToRef = function (array, offset, result) {
  3109. result.x = array[offset];
  3110. result.y = array[offset + 1];
  3111. result.z = array[offset + 2];
  3112. };
  3113. /**
  3114. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3115. * This function is deprecated. Use FromArrayToRef instead.
  3116. * @param array defines the source array
  3117. * @param offset defines the offset in the source array
  3118. * @param result defines the Vector3 where to store the result
  3119. */
  3120. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3121. return Vector3.FromArrayToRef(array, offset, result);
  3122. };
  3123. /**
  3124. * Sets the passed vector "result" with the passed floats.
  3125. * @param x defines the x coordinate of the source
  3126. * @param y defines the y coordinate of the source
  3127. * @param z defines the z coordinate of the source
  3128. * @param result defines the Vector3 where to store the result
  3129. */
  3130. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3131. result.x = x;
  3132. result.y = y;
  3133. result.z = z;
  3134. };
  3135. /**
  3136. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3137. * @returns a new empty Vector3
  3138. */
  3139. Vector3.Zero = function () {
  3140. return new Vector3(0.0, 0.0, 0.0);
  3141. };
  3142. /**
  3143. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3144. * @returns a new unit Vector3
  3145. */
  3146. Vector3.One = function () {
  3147. return new Vector3(1.0, 1.0, 1.0);
  3148. };
  3149. /**
  3150. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3151. * @returns a new up Vector3
  3152. */
  3153. Vector3.Up = function () {
  3154. return new Vector3(0.0, 1.0, 0.0);
  3155. };
  3156. /**
  3157. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3158. * @returns a new forward Vector3
  3159. */
  3160. Vector3.Forward = function () {
  3161. return new Vector3(0.0, 0.0, 1.0);
  3162. };
  3163. /**
  3164. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3165. * @returns a new right Vector3
  3166. */
  3167. Vector3.Right = function () {
  3168. return new Vector3(1.0, 0.0, 0.0);
  3169. };
  3170. /**
  3171. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3172. * @returns a new left Vector3
  3173. */
  3174. Vector3.Left = function () {
  3175. return new Vector3(-1.0, 0.0, 0.0);
  3176. };
  3177. /**
  3178. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3179. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3180. * @param vector defines the Vector3 to transform
  3181. * @param transformation defines the transformation matrix
  3182. * @returns the transformed Vector3
  3183. */
  3184. Vector3.TransformCoordinates = function (vector, transformation) {
  3185. var result = Vector3.Zero();
  3186. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3187. return result;
  3188. };
  3189. /**
  3190. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3191. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3192. * @param vector defines the Vector3 to transform
  3193. * @param transformation defines the transformation matrix
  3194. * @param result defines the Vector3 where to store the result
  3195. */
  3196. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3197. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3198. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3199. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3200. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3201. result.x = x / w;
  3202. result.y = y / w;
  3203. result.z = z / w;
  3204. };
  3205. /**
  3206. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3207. * This method computes tranformed coordinates only, not transformed direction vectors
  3208. * @param x define the x coordinate of the source vector
  3209. * @param y define the y coordinate of the source vector
  3210. * @param z define the z coordinate of the source vector
  3211. * @param transformation defines the transformation matrix
  3212. * @param result defines the Vector3 where to store the result
  3213. */
  3214. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3215. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3216. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3217. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3218. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3219. result.x = rx / rw;
  3220. result.y = ry / rw;
  3221. result.z = rz / rw;
  3222. };
  3223. /**
  3224. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3225. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3226. * @param vector defines the Vector3 to transform
  3227. * @param transformation defines the transformation matrix
  3228. * @returns the new Vector3
  3229. */
  3230. Vector3.TransformNormal = function (vector, transformation) {
  3231. var result = Vector3.Zero();
  3232. Vector3.TransformNormalToRef(vector, transformation, result);
  3233. return result;
  3234. };
  3235. /**
  3236. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3237. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3238. * @param vector defines the Vector3 to transform
  3239. * @param transformation defines the transformation matrix
  3240. * @param result defines the Vector3 where to store the result
  3241. */
  3242. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3243. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3244. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3245. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3246. result.x = x;
  3247. result.y = y;
  3248. result.z = z;
  3249. };
  3250. /**
  3251. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3252. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3253. * @param x define the x coordinate of the source vector
  3254. * @param y define the y coordinate of the source vector
  3255. * @param z define the z coordinate of the source vector
  3256. * @param transformation defines the transformation matrix
  3257. * @param result defines the Vector3 where to store the result
  3258. */
  3259. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3260. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3261. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3262. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3263. };
  3264. /**
  3265. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3266. * @param value1 defines the first control point
  3267. * @param value2 defines the second control point
  3268. * @param value3 defines the third control point
  3269. * @param value4 defines the fourth control point
  3270. * @param amount defines the amount on the spline to use
  3271. * @returns the new Vector3
  3272. */
  3273. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3274. var squared = amount * amount;
  3275. var cubed = amount * squared;
  3276. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3277. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3278. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3279. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3280. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3281. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3282. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3283. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3284. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3285. return new Vector3(x, y, z);
  3286. };
  3287. /**
  3288. * 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"
  3289. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3290. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3291. * @param value defines the current value
  3292. * @param min defines the lower range value
  3293. * @param max defines the upper range value
  3294. * @returns the new Vector3
  3295. */
  3296. Vector3.Clamp = function (value, min, max) {
  3297. var x = value.x;
  3298. x = (x > max.x) ? max.x : x;
  3299. x = (x < min.x) ? min.x : x;
  3300. var y = value.y;
  3301. y = (y > max.y) ? max.y : y;
  3302. y = (y < min.y) ? min.y : y;
  3303. var z = value.z;
  3304. z = (z > max.z) ? max.z : z;
  3305. z = (z < min.z) ? min.z : z;
  3306. return new Vector3(x, y, z);
  3307. };
  3308. /**
  3309. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3310. * @param value1 defines the first control point
  3311. * @param tangent1 defines the first tangent vector
  3312. * @param value2 defines the second control point
  3313. * @param tangent2 defines the second tangent vector
  3314. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3315. * @returns the new Vector3
  3316. */
  3317. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3318. var squared = amount * amount;
  3319. var cubed = amount * squared;
  3320. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3321. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3322. var part3 = (cubed - (2.0 * squared)) + amount;
  3323. var part4 = cubed - squared;
  3324. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3325. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3326. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3327. return new Vector3(x, y, z);
  3328. };
  3329. /**
  3330. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3331. * @param start defines the start value
  3332. * @param end defines the end value
  3333. * @param amount max defines amount between both (between 0 and 1)
  3334. * @returns the new Vector3
  3335. */
  3336. Vector3.Lerp = function (start, end, amount) {
  3337. var result = new Vector3(0, 0, 0);
  3338. Vector3.LerpToRef(start, end, amount, result);
  3339. return result;
  3340. };
  3341. /**
  3342. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3343. * @param start defines the start value
  3344. * @param end defines the end value
  3345. * @param amount max defines amount between both (between 0 and 1)
  3346. * @param result defines the Vector3 where to store the result
  3347. */
  3348. Vector3.LerpToRef = function (start, end, amount, result) {
  3349. result.x = start.x + ((end.x - start.x) * amount);
  3350. result.y = start.y + ((end.y - start.y) * amount);
  3351. result.z = start.z + ((end.z - start.z) * amount);
  3352. };
  3353. /**
  3354. * Returns the dot product (float) between the vectors "left" and "right"
  3355. * @param left defines the left operand
  3356. * @param right defines the right operand
  3357. * @returns the dot product
  3358. */
  3359. Vector3.Dot = function (left, right) {
  3360. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3361. };
  3362. /**
  3363. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3364. * The cross product is then orthogonal to both "left" and "right"
  3365. * @param left defines the left operand
  3366. * @param right defines the right operand
  3367. * @returns the cross product
  3368. */
  3369. Vector3.Cross = function (left, right) {
  3370. var result = Vector3.Zero();
  3371. Vector3.CrossToRef(left, right, result);
  3372. return result;
  3373. };
  3374. /**
  3375. * Sets the passed vector "result" with the cross product of "left" and "right"
  3376. * The cross product is then orthogonal to both "left" and "right"
  3377. * @param left defines the left operand
  3378. * @param right defines the right operand
  3379. * @param result defines the Vector3 where to store the result
  3380. */
  3381. Vector3.CrossToRef = function (left, right, result) {
  3382. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3383. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3384. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3385. result.copyFrom(MathTmp.Vector3[0]);
  3386. };
  3387. /**
  3388. * Returns a new Vector3 as the normalization of the passed vector
  3389. * @param vector defines the Vector3 to normalize
  3390. * @returns the new Vector3
  3391. */
  3392. Vector3.Normalize = function (vector) {
  3393. var result = Vector3.Zero();
  3394. Vector3.NormalizeToRef(vector, result);
  3395. return result;
  3396. };
  3397. /**
  3398. * Sets the passed vector "result" with the normalization of the passed first vector
  3399. * @param vector defines the Vector3 to normalize
  3400. * @param result defines the Vector3 where to store the result
  3401. */
  3402. Vector3.NormalizeToRef = function (vector, result) {
  3403. result.copyFrom(vector);
  3404. result.normalize();
  3405. };
  3406. /**
  3407. * Project a Vector3 onto screen space
  3408. * @param vector defines the Vector3 to project
  3409. * @param world defines the world matrix to use
  3410. * @param transform defines the transform (view x projection) matrix to use
  3411. * @param viewport defines the screen viewport to use
  3412. * @returns the new Vector3
  3413. */
  3414. Vector3.Project = function (vector, world, transform, viewport) {
  3415. var cw = viewport.width;
  3416. var ch = viewport.height;
  3417. var cx = viewport.x;
  3418. var cy = viewport.y;
  3419. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3420. 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);
  3421. var matrix = MathTmp.Matrix[0];
  3422. world.multiplyToRef(transform, matrix);
  3423. matrix.multiplyToRef(viewportMatrix, matrix);
  3424. return Vector3.TransformCoordinates(vector, matrix);
  3425. };
  3426. /**
  3427. * Unproject from screen space to object space
  3428. * @param source defines the screen space Vector3 to use
  3429. * @param viewportWidth defines the current width of the viewport
  3430. * @param viewportHeight defines the current height of the viewport
  3431. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3432. * @param transform defines the transform (view x projection) matrix to use
  3433. * @returns the new Vector3
  3434. */
  3435. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3436. var matrix = MathTmp.Matrix[0];
  3437. world.multiplyToRef(transform, matrix);
  3438. matrix.invert();
  3439. source.x = source.x / viewportWidth * 2 - 1;
  3440. source.y = -(source.y / viewportHeight * 2 - 1);
  3441. var vector = Vector3.TransformCoordinates(source, matrix);
  3442. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3443. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3444. vector = vector.scale(1.0 / num);
  3445. }
  3446. return vector;
  3447. };
  3448. /**
  3449. * Unproject from screen space to object space
  3450. * @param source defines the screen space Vector3 to use
  3451. * @param viewportWidth defines the current width of the viewport
  3452. * @param viewportHeight defines the current height of the viewport
  3453. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3454. * @param view defines the view matrix to use
  3455. * @param projection defines the projection matrix to use
  3456. * @returns the new Vector3
  3457. */
  3458. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3459. var result = Vector3.Zero();
  3460. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3461. return result;
  3462. };
  3463. /**
  3464. * Unproject from screen space to object space
  3465. * @param source defines the screen space Vector3 to use
  3466. * @param viewportWidth defines the current width of the viewport
  3467. * @param viewportHeight defines the current height of the viewport
  3468. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3469. * @param view defines the view matrix to use
  3470. * @param projection defines the projection matrix to use
  3471. * @param result defines the Vector3 where to store the result
  3472. */
  3473. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3474. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3475. };
  3476. /**
  3477. * Unproject from screen space to object space
  3478. * @param sourceX defines the screen space x coordinate to use
  3479. * @param sourceY defines the screen space y coordinate to use
  3480. * @param sourceZ defines the screen space z coordinate to use
  3481. * @param viewportWidth defines the current width of the viewport
  3482. * @param viewportHeight defines the current height of the viewport
  3483. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3484. * @param view defines the view matrix to use
  3485. * @param projection defines the projection matrix to use
  3486. * @param result defines the Vector3 where to store the result
  3487. */
  3488. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3489. var matrix = MathTmp.Matrix[0];
  3490. world.multiplyToRef(view, matrix);
  3491. matrix.multiplyToRef(projection, matrix);
  3492. matrix.invert();
  3493. var screenSource = MathTmp.Vector3[0];
  3494. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3495. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3496. screenSource.z = 2 * sourceZ - 1.0;
  3497. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3498. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3499. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3500. result.scaleInPlace(1.0 / num);
  3501. }
  3502. };
  3503. /**
  3504. * Gets the minimal coordinate values between two Vector3
  3505. * @param left defines the first operand
  3506. * @param right defines the second operand
  3507. * @returns the new Vector3
  3508. */
  3509. Vector3.Minimize = function (left, right) {
  3510. var min = left.clone();
  3511. min.minimizeInPlace(right);
  3512. return min;
  3513. };
  3514. /**
  3515. * Gets the maximal coordinate values between two Vector3
  3516. * @param left defines the first operand
  3517. * @param right defines the second operand
  3518. * @returns the new Vector3
  3519. */
  3520. Vector3.Maximize = function (left, right) {
  3521. var max = left.clone();
  3522. max.maximizeInPlace(right);
  3523. return max;
  3524. };
  3525. /**
  3526. * Returns the distance between the vectors "value1" and "value2"
  3527. * @param value1 defines the first operand
  3528. * @param value2 defines the second operand
  3529. * @returns the distance
  3530. */
  3531. Vector3.Distance = function (value1, value2) {
  3532. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3533. };
  3534. /**
  3535. * Returns the squared distance between the vectors "value1" and "value2"
  3536. * @param value1 defines the first operand
  3537. * @param value2 defines the second operand
  3538. * @returns the squared distance
  3539. */
  3540. Vector3.DistanceSquared = function (value1, value2) {
  3541. var x = value1.x - value2.x;
  3542. var y = value1.y - value2.y;
  3543. var z = value1.z - value2.z;
  3544. return (x * x) + (y * y) + (z * z);
  3545. };
  3546. /**
  3547. * Returns a new Vector3 located at the center between "value1" and "value2"
  3548. * @param value1 defines the first operand
  3549. * @param value2 defines the second operand
  3550. * @returns the new Vector3
  3551. */
  3552. Vector3.Center = function (value1, value2) {
  3553. var center = value1.add(value2);
  3554. center.scaleInPlace(0.5);
  3555. return center;
  3556. };
  3557. /**
  3558. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3559. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3560. * to something in order to rotate it from its local system to the given target system
  3561. * Note: axis1, axis2 and axis3 are normalized during this operation
  3562. * @param axis1 defines the first axis
  3563. * @param axis2 defines the second axis
  3564. * @param axis3 defines the third axis
  3565. * @returns a new Vector3
  3566. */
  3567. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3568. var rotation = Vector3.Zero();
  3569. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3570. return rotation;
  3571. };
  3572. /**
  3573. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3574. * @param axis1 defines the first axis
  3575. * @param axis2 defines the second axis
  3576. * @param axis3 defines the third axis
  3577. * @param ref defines the Vector3 where to store the result
  3578. */
  3579. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3580. var quat = MathTmp.Quaternion[0];
  3581. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3582. quat.toEulerAnglesToRef(ref);
  3583. };
  3584. return Vector3;
  3585. }());
  3586. BABYLON.Vector3 = Vector3;
  3587. //Vector4 class created for EulerAngle class conversion to Quaternion
  3588. var Vector4 = /** @class */ (function () {
  3589. /**
  3590. * Creates a Vector4 object from the passed floats.
  3591. */
  3592. function Vector4(x, y, z, w) {
  3593. this.x = x;
  3594. this.y = y;
  3595. this.z = z;
  3596. this.w = w;
  3597. }
  3598. /**
  3599. * Returns the string with the Vector4 coordinates.
  3600. */
  3601. Vector4.prototype.toString = function () {
  3602. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3603. };
  3604. /**
  3605. * Returns the string "Vector4".
  3606. */
  3607. Vector4.prototype.getClassName = function () {
  3608. return "Vector4";
  3609. };
  3610. /**
  3611. * Returns the Vector4 hash code.
  3612. */
  3613. Vector4.prototype.getHashCode = function () {
  3614. var hash = this.x || 0;
  3615. hash = (hash * 397) ^ (this.y || 0);
  3616. hash = (hash * 397) ^ (this.z || 0);
  3617. hash = (hash * 397) ^ (this.w || 0);
  3618. return hash;
  3619. };
  3620. // Operators
  3621. /**
  3622. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3623. */
  3624. Vector4.prototype.asArray = function () {
  3625. var result = new Array();
  3626. this.toArray(result, 0);
  3627. return result;
  3628. };
  3629. /**
  3630. * Populates the passed array from the passed index with the Vector4 coordinates.
  3631. * Returns the Vector4.
  3632. */
  3633. Vector4.prototype.toArray = function (array, index) {
  3634. if (index === undefined) {
  3635. index = 0;
  3636. }
  3637. array[index] = this.x;
  3638. array[index + 1] = this.y;
  3639. array[index + 2] = this.z;
  3640. array[index + 3] = this.w;
  3641. return this;
  3642. };
  3643. /**
  3644. * Adds the passed vector to the current Vector4.
  3645. * Returns the updated Vector4.
  3646. */
  3647. Vector4.prototype.addInPlace = function (otherVector) {
  3648. this.x += otherVector.x;
  3649. this.y += otherVector.y;
  3650. this.z += otherVector.z;
  3651. this.w += otherVector.w;
  3652. return this;
  3653. };
  3654. /**
  3655. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3656. */
  3657. Vector4.prototype.add = function (otherVector) {
  3658. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3659. };
  3660. /**
  3661. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3662. * Returns the current Vector4.
  3663. */
  3664. Vector4.prototype.addToRef = function (otherVector, result) {
  3665. result.x = this.x + otherVector.x;
  3666. result.y = this.y + otherVector.y;
  3667. result.z = this.z + otherVector.z;
  3668. result.w = this.w + otherVector.w;
  3669. return this;
  3670. };
  3671. /**
  3672. * Subtract in place the passed vector from the current Vector4.
  3673. * Returns the updated Vector4.
  3674. */
  3675. Vector4.prototype.subtractInPlace = function (otherVector) {
  3676. this.x -= otherVector.x;
  3677. this.y -= otherVector.y;
  3678. this.z -= otherVector.z;
  3679. this.w -= otherVector.w;
  3680. return this;
  3681. };
  3682. /**
  3683. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3684. */
  3685. Vector4.prototype.subtract = function (otherVector) {
  3686. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3687. };
  3688. /**
  3689. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3690. * Returns the current Vector4.
  3691. */
  3692. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3693. result.x = this.x - otherVector.x;
  3694. result.y = this.y - otherVector.y;
  3695. result.z = this.z - otherVector.z;
  3696. result.w = this.w - otherVector.w;
  3697. return this;
  3698. };
  3699. /**
  3700. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3701. */
  3702. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3703. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3704. };
  3705. /**
  3706. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3707. * Returns the current Vector4.
  3708. */
  3709. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3710. result.x = this.x - x;
  3711. result.y = this.y - y;
  3712. result.z = this.z - z;
  3713. result.w = this.w - w;
  3714. return this;
  3715. };
  3716. /**
  3717. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3718. */
  3719. Vector4.prototype.negate = function () {
  3720. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3721. };
  3722. /**
  3723. * Multiplies the current Vector4 coordinates by scale (float).
  3724. * Returns the updated Vector4.
  3725. */
  3726. Vector4.prototype.scaleInPlace = function (scale) {
  3727. this.x *= scale;
  3728. this.y *= scale;
  3729. this.z *= scale;
  3730. this.w *= scale;
  3731. return this;
  3732. };
  3733. /**
  3734. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3735. */
  3736. Vector4.prototype.scale = function (scale) {
  3737. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3738. };
  3739. /**
  3740. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3741. * Returns the current Vector4.
  3742. */
  3743. Vector4.prototype.scaleToRef = function (scale, result) {
  3744. result.x = this.x * scale;
  3745. result.y = this.y * scale;
  3746. result.z = this.z * scale;
  3747. result.w = this.w * scale;
  3748. return this;
  3749. };
  3750. /**
  3751. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3752. */
  3753. Vector4.prototype.equals = function (otherVector) {
  3754. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3755. };
  3756. /**
  3757. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3758. */
  3759. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3760. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3761. return otherVector
  3762. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3763. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3764. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3765. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3766. };
  3767. /**
  3768. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3769. */
  3770. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3771. return this.x === x && this.y === y && this.z === z && this.w === w;
  3772. };
  3773. /**
  3774. * Multiplies in place the current Vector4 by the passed one.
  3775. * Returns the updated Vector4.
  3776. */
  3777. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3778. this.x *= otherVector.x;
  3779. this.y *= otherVector.y;
  3780. this.z *= otherVector.z;
  3781. this.w *= otherVector.w;
  3782. return this;
  3783. };
  3784. /**
  3785. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3786. */
  3787. Vector4.prototype.multiply = function (otherVector) {
  3788. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3789. };
  3790. /**
  3791. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3792. * Returns the current Vector4.
  3793. */
  3794. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3795. result.x = this.x * otherVector.x;
  3796. result.y = this.y * otherVector.y;
  3797. result.z = this.z * otherVector.z;
  3798. result.w = this.w * otherVector.w;
  3799. return this;
  3800. };
  3801. /**
  3802. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3803. */
  3804. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3805. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3806. };
  3807. /**
  3808. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3809. */
  3810. Vector4.prototype.divide = function (otherVector) {
  3811. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3812. };
  3813. /**
  3814. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3815. * Returns the current Vector4.
  3816. */
  3817. Vector4.prototype.divideToRef = function (otherVector, result) {
  3818. result.x = this.x / otherVector.x;
  3819. result.y = this.y / otherVector.y;
  3820. result.z = this.z / otherVector.z;
  3821. result.w = this.w / otherVector.w;
  3822. return this;
  3823. };
  3824. /**
  3825. * Divides the current Vector3 coordinates by the passed ones.
  3826. * @returns the updated Vector3.
  3827. */
  3828. Vector4.prototype.divideInPlace = function (otherVector) {
  3829. return this.divideToRef(otherVector, this);
  3830. };
  3831. /**
  3832. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3833. * @param other defines the second operand
  3834. * @returns the current updated Vector4
  3835. */
  3836. Vector4.prototype.minimizeInPlace = function (other) {
  3837. if (other.x < this.x)
  3838. this.x = other.x;
  3839. if (other.y < this.y)
  3840. this.y = other.y;
  3841. if (other.z < this.z)
  3842. this.z = other.z;
  3843. if (other.w < this.w)
  3844. this.w = other.w;
  3845. return this;
  3846. };
  3847. /**
  3848. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3849. * @param other defines the second operand
  3850. * @returns the current updated Vector4
  3851. */
  3852. Vector4.prototype.maximizeInPlace = function (other) {
  3853. if (other.x > this.x)
  3854. this.x = other.x;
  3855. if (other.y > this.y)
  3856. this.y = other.y;
  3857. if (other.z > this.z)
  3858. this.z = other.z;
  3859. if (other.w > this.w)
  3860. this.w = other.w;
  3861. return this;
  3862. };
  3863. // Properties
  3864. /**
  3865. * Returns the Vector4 length (float).
  3866. */
  3867. Vector4.prototype.length = function () {
  3868. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3869. };
  3870. /**
  3871. * Returns the Vector4 squared length (float).
  3872. */
  3873. Vector4.prototype.lengthSquared = function () {
  3874. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3875. };
  3876. // Methods
  3877. /**
  3878. * Normalizes in place the Vector4.
  3879. * Returns the updated Vector4.
  3880. */
  3881. Vector4.prototype.normalize = function () {
  3882. var len = this.length();
  3883. if (len === 0)
  3884. return this;
  3885. var num = 1.0 / len;
  3886. this.x *= num;
  3887. this.y *= num;
  3888. this.z *= num;
  3889. this.w *= num;
  3890. return this;
  3891. };
  3892. /**
  3893. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3894. */
  3895. Vector4.prototype.toVector3 = function () {
  3896. return new Vector3(this.x, this.y, this.z);
  3897. };
  3898. /**
  3899. * Returns a new Vector4 copied from the current one.
  3900. */
  3901. Vector4.prototype.clone = function () {
  3902. return new Vector4(this.x, this.y, this.z, this.w);
  3903. };
  3904. /**
  3905. * Updates the current Vector4 with the passed one coordinates.
  3906. * Returns the updated Vector4.
  3907. */
  3908. Vector4.prototype.copyFrom = function (source) {
  3909. this.x = source.x;
  3910. this.y = source.y;
  3911. this.z = source.z;
  3912. this.w = source.w;
  3913. return this;
  3914. };
  3915. /**
  3916. * Updates the current Vector4 coordinates with the passed floats.
  3917. * Returns the updated Vector4.
  3918. */
  3919. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3920. this.x = x;
  3921. this.y = y;
  3922. this.z = z;
  3923. this.w = w;
  3924. return this;
  3925. };
  3926. /**
  3927. * Updates the current Vector4 coordinates with the passed floats.
  3928. * Returns the updated Vector4.
  3929. */
  3930. Vector4.prototype.set = function (x, y, z, w) {
  3931. return this.copyFromFloats(x, y, z, w);
  3932. };
  3933. // Statics
  3934. /**
  3935. * Returns a new Vector4 set from the starting index of the passed array.
  3936. */
  3937. Vector4.FromArray = function (array, offset) {
  3938. if (!offset) {
  3939. offset = 0;
  3940. }
  3941. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3942. };
  3943. /**
  3944. * Updates the passed vector "result" from the starting index of the passed array.
  3945. */
  3946. Vector4.FromArrayToRef = function (array, offset, result) {
  3947. result.x = array[offset];
  3948. result.y = array[offset + 1];
  3949. result.z = array[offset + 2];
  3950. result.w = array[offset + 3];
  3951. };
  3952. /**
  3953. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3954. */
  3955. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3956. Vector4.FromArrayToRef(array, offset, result);
  3957. };
  3958. /**
  3959. * Updates the passed vector "result" coordinates from the passed floats.
  3960. */
  3961. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3962. result.x = x;
  3963. result.y = y;
  3964. result.z = z;
  3965. result.w = w;
  3966. };
  3967. /**
  3968. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3969. */
  3970. Vector4.Zero = function () {
  3971. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3972. };
  3973. /**
  3974. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3975. */
  3976. Vector4.One = function () {
  3977. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3978. };
  3979. /**
  3980. * Returns a new normalized Vector4 from the passed one.
  3981. */
  3982. Vector4.Normalize = function (vector) {
  3983. var result = Vector4.Zero();
  3984. Vector4.NormalizeToRef(vector, result);
  3985. return result;
  3986. };
  3987. /**
  3988. * Updates the passed vector "result" from the normalization of the passed one.
  3989. */
  3990. Vector4.NormalizeToRef = function (vector, result) {
  3991. result.copyFrom(vector);
  3992. result.normalize();
  3993. };
  3994. Vector4.Minimize = function (left, right) {
  3995. var min = left.clone();
  3996. min.minimizeInPlace(right);
  3997. return min;
  3998. };
  3999. Vector4.Maximize = function (left, right) {
  4000. var max = left.clone();
  4001. max.maximizeInPlace(right);
  4002. return max;
  4003. };
  4004. /**
  4005. * Returns the distance (float) between the vectors "value1" and "value2".
  4006. */
  4007. Vector4.Distance = function (value1, value2) {
  4008. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4009. };
  4010. /**
  4011. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4012. */
  4013. Vector4.DistanceSquared = function (value1, value2) {
  4014. var x = value1.x - value2.x;
  4015. var y = value1.y - value2.y;
  4016. var z = value1.z - value2.z;
  4017. var w = value1.w - value2.w;
  4018. return (x * x) + (y * y) + (z * z) + (w * w);
  4019. };
  4020. /**
  4021. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4022. */
  4023. Vector4.Center = function (value1, value2) {
  4024. var center = value1.add(value2);
  4025. center.scaleInPlace(0.5);
  4026. return center;
  4027. };
  4028. /**
  4029. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4030. * This methods computes transformed normalized direction vectors only.
  4031. */
  4032. Vector4.TransformNormal = function (vector, transformation) {
  4033. var result = Vector4.Zero();
  4034. Vector4.TransformNormalToRef(vector, transformation, result);
  4035. return result;
  4036. };
  4037. /**
  4038. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4039. * This methods computes transformed normalized direction vectors only.
  4040. */
  4041. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4042. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4043. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4044. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4045. result.x = x;
  4046. result.y = y;
  4047. result.z = z;
  4048. result.w = vector.w;
  4049. };
  4050. /**
  4051. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4052. * This methods computes transformed normalized direction vectors only.
  4053. */
  4054. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4055. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4056. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4057. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4058. result.w = w;
  4059. };
  4060. return Vector4;
  4061. }());
  4062. BABYLON.Vector4 = Vector4;
  4063. var Size = /** @class */ (function () {
  4064. /**
  4065. * Creates a Size object from the passed width and height (floats).
  4066. */
  4067. function Size(width, height) {
  4068. this.width = width;
  4069. this.height = height;
  4070. }
  4071. // Returns a string with the Size width and height.
  4072. Size.prototype.toString = function () {
  4073. return "{W: " + this.width + ", H: " + this.height + "}";
  4074. };
  4075. /**
  4076. * Returns the string "Size"
  4077. */
  4078. Size.prototype.getClassName = function () {
  4079. return "Size";
  4080. };
  4081. /**
  4082. * Returns the Size hash code.
  4083. */
  4084. Size.prototype.getHashCode = function () {
  4085. var hash = this.width || 0;
  4086. hash = (hash * 397) ^ (this.height || 0);
  4087. return hash;
  4088. };
  4089. /**
  4090. * Updates the current size from the passed one.
  4091. * Returns the updated Size.
  4092. */
  4093. Size.prototype.copyFrom = function (src) {
  4094. this.width = src.width;
  4095. this.height = src.height;
  4096. };
  4097. /**
  4098. * Updates in place the current Size from the passed floats.
  4099. * Returns the updated Size.
  4100. */
  4101. Size.prototype.copyFromFloats = function (width, height) {
  4102. this.width = width;
  4103. this.height = height;
  4104. return this;
  4105. };
  4106. /**
  4107. * Updates in place the current Size from the passed floats.
  4108. * Returns the updated Size.
  4109. */
  4110. Size.prototype.set = function (width, height) {
  4111. return this.copyFromFloats(width, height);
  4112. };
  4113. /**
  4114. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4115. */
  4116. Size.prototype.multiplyByFloats = function (w, h) {
  4117. return new Size(this.width * w, this.height * h);
  4118. };
  4119. /**
  4120. * Returns a new Size copied from the passed one.
  4121. */
  4122. Size.prototype.clone = function () {
  4123. return new Size(this.width, this.height);
  4124. };
  4125. /**
  4126. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4127. */
  4128. Size.prototype.equals = function (other) {
  4129. if (!other) {
  4130. return false;
  4131. }
  4132. return (this.width === other.width) && (this.height === other.height);
  4133. };
  4134. Object.defineProperty(Size.prototype, "surface", {
  4135. /**
  4136. * Returns the surface of the Size : width * height (float).
  4137. */
  4138. get: function () {
  4139. return this.width * this.height;
  4140. },
  4141. enumerable: true,
  4142. configurable: true
  4143. });
  4144. /**
  4145. * Returns a new Size set to (0.0, 0.0)
  4146. */
  4147. Size.Zero = function () {
  4148. return new Size(0.0, 0.0);
  4149. };
  4150. /**
  4151. * Returns a new Size set as the addition result of the current Size and the passed one.
  4152. */
  4153. Size.prototype.add = function (otherSize) {
  4154. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4155. return r;
  4156. };
  4157. /**
  4158. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4159. */
  4160. Size.prototype.subtract = function (otherSize) {
  4161. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4162. return r;
  4163. };
  4164. /**
  4165. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4166. */
  4167. Size.Lerp = function (start, end, amount) {
  4168. var w = start.width + ((end.width - start.width) * amount);
  4169. var h = start.height + ((end.height - start.height) * amount);
  4170. return new Size(w, h);
  4171. };
  4172. return Size;
  4173. }());
  4174. BABYLON.Size = Size;
  4175. var Quaternion = /** @class */ (function () {
  4176. /**
  4177. * Creates a new Quaternion from the passed floats.
  4178. */
  4179. function Quaternion(x, y, z, w) {
  4180. if (x === void 0) { x = 0.0; }
  4181. if (y === void 0) { y = 0.0; }
  4182. if (z === void 0) { z = 0.0; }
  4183. if (w === void 0) { w = 1.0; }
  4184. this.x = x;
  4185. this.y = y;
  4186. this.z = z;
  4187. this.w = w;
  4188. }
  4189. /**
  4190. * Returns a string with the Quaternion coordinates.
  4191. */
  4192. Quaternion.prototype.toString = function () {
  4193. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4194. };
  4195. /**
  4196. * Returns the string "Quaternion".
  4197. */
  4198. Quaternion.prototype.getClassName = function () {
  4199. return "Quaternion";
  4200. };
  4201. /**
  4202. * Returns the Quaternion hash code.
  4203. */
  4204. Quaternion.prototype.getHashCode = function () {
  4205. var hash = this.x || 0;
  4206. hash = (hash * 397) ^ (this.y || 0);
  4207. hash = (hash * 397) ^ (this.z || 0);
  4208. hash = (hash * 397) ^ (this.w || 0);
  4209. return hash;
  4210. };
  4211. /**
  4212. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4213. */
  4214. Quaternion.prototype.asArray = function () {
  4215. return [this.x, this.y, this.z, this.w];
  4216. };
  4217. /**
  4218. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4219. */
  4220. Quaternion.prototype.equals = function (otherQuaternion) {
  4221. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4222. };
  4223. /**
  4224. * Returns a new Quaternion copied from the current one.
  4225. */
  4226. Quaternion.prototype.clone = function () {
  4227. return new Quaternion(this.x, this.y, this.z, this.w);
  4228. };
  4229. /**
  4230. * Updates the current Quaternion from the passed one coordinates.
  4231. * Returns the updated Quaterion.
  4232. */
  4233. Quaternion.prototype.copyFrom = function (other) {
  4234. this.x = other.x;
  4235. this.y = other.y;
  4236. this.z = other.z;
  4237. this.w = other.w;
  4238. return this;
  4239. };
  4240. /**
  4241. * Updates the current Quaternion from the passed float coordinates.
  4242. * Returns the updated Quaterion.
  4243. */
  4244. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4245. this.x = x;
  4246. this.y = y;
  4247. this.z = z;
  4248. this.w = w;
  4249. return this;
  4250. };
  4251. /**
  4252. * Updates the current Quaternion from the passed float coordinates.
  4253. * Returns the updated Quaterion.
  4254. */
  4255. Quaternion.prototype.set = function (x, y, z, w) {
  4256. return this.copyFromFloats(x, y, z, w);
  4257. };
  4258. /**
  4259. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4260. */
  4261. Quaternion.prototype.add = function (other) {
  4262. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4263. };
  4264. /**
  4265. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4266. */
  4267. Quaternion.prototype.subtract = function (other) {
  4268. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4269. };
  4270. /**
  4271. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4272. */
  4273. Quaternion.prototype.scale = function (value) {
  4274. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4275. };
  4276. /**
  4277. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4278. */
  4279. Quaternion.prototype.multiply = function (q1) {
  4280. var result = new Quaternion(0, 0, 0, 1.0);
  4281. this.multiplyToRef(q1, result);
  4282. return result;
  4283. };
  4284. /**
  4285. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4286. * Returns the current Quaternion.
  4287. */
  4288. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4289. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4290. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4291. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4292. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4293. result.copyFromFloats(x, y, z, w);
  4294. return this;
  4295. };
  4296. /**
  4297. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4298. * Returns the updated Quaternion.
  4299. */
  4300. Quaternion.prototype.multiplyInPlace = function (q1) {
  4301. this.multiplyToRef(q1, this);
  4302. return this;
  4303. };
  4304. /**
  4305. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4306. * Returns the current Quaternion.
  4307. */
  4308. Quaternion.prototype.conjugateToRef = function (ref) {
  4309. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4310. return this;
  4311. };
  4312. /**
  4313. * Conjugates in place the current Quaternion.
  4314. * Returns the updated Quaternion.
  4315. */
  4316. Quaternion.prototype.conjugateInPlace = function () {
  4317. this.x *= -1;
  4318. this.y *= -1;
  4319. this.z *= -1;
  4320. return this;
  4321. };
  4322. /**
  4323. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4324. */
  4325. Quaternion.prototype.conjugate = function () {
  4326. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4327. return result;
  4328. };
  4329. /**
  4330. * Returns the Quaternion length (float).
  4331. */
  4332. Quaternion.prototype.length = function () {
  4333. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4334. };
  4335. /**
  4336. * Normalize in place the current Quaternion.
  4337. * Returns the updated Quaternion.
  4338. */
  4339. Quaternion.prototype.normalize = function () {
  4340. var length = 1.0 / this.length();
  4341. this.x *= length;
  4342. this.y *= length;
  4343. this.z *= length;
  4344. this.w *= length;
  4345. return this;
  4346. };
  4347. /**
  4348. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4349. */
  4350. Quaternion.prototype.toEulerAngles = function (order) {
  4351. if (order === void 0) { order = "YZX"; }
  4352. var result = Vector3.Zero();
  4353. this.toEulerAnglesToRef(result, order);
  4354. return result;
  4355. };
  4356. /**
  4357. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4358. * Returns the current Quaternion.
  4359. */
  4360. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4361. if (order === void 0) { order = "YZX"; }
  4362. var qz = this.z;
  4363. var qx = this.x;
  4364. var qy = this.y;
  4365. var qw = this.w;
  4366. var sqw = qw * qw;
  4367. var sqz = qz * qz;
  4368. var sqx = qx * qx;
  4369. var sqy = qy * qy;
  4370. var zAxisY = qy * qz - qx * qw;
  4371. var limit = .4999999;
  4372. if (zAxisY < -limit) {
  4373. result.y = 2 * Math.atan2(qy, qw);
  4374. result.x = Math.PI / 2;
  4375. result.z = 0;
  4376. }
  4377. else if (zAxisY > limit) {
  4378. result.y = 2 * Math.atan2(qy, qw);
  4379. result.x = -Math.PI / 2;
  4380. result.z = 0;
  4381. }
  4382. else {
  4383. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4384. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4385. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4386. }
  4387. return this;
  4388. };
  4389. /**
  4390. * Updates the passed rotation matrix with the current Quaternion values.
  4391. * Returns the current Quaternion.
  4392. */
  4393. Quaternion.prototype.toRotationMatrix = function (result) {
  4394. var xx = this.x * this.x;
  4395. var yy = this.y * this.y;
  4396. var zz = this.z * this.z;
  4397. var xy = this.x * this.y;
  4398. var zw = this.z * this.w;
  4399. var zx = this.z * this.x;
  4400. var yw = this.y * this.w;
  4401. var yz = this.y * this.z;
  4402. var xw = this.x * this.w;
  4403. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4404. result.m[1] = 2.0 * (xy + zw);
  4405. result.m[2] = 2.0 * (zx - yw);
  4406. result.m[3] = 0;
  4407. result.m[4] = 2.0 * (xy - zw);
  4408. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4409. result.m[6] = 2.0 * (yz + xw);
  4410. result.m[7] = 0;
  4411. result.m[8] = 2.0 * (zx + yw);
  4412. result.m[9] = 2.0 * (yz - xw);
  4413. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4414. result.m[11] = 0;
  4415. result.m[12] = 0;
  4416. result.m[13] = 0;
  4417. result.m[14] = 0;
  4418. result.m[15] = 1.0;
  4419. result._markAsUpdated();
  4420. return this;
  4421. };
  4422. /**
  4423. * Updates the current Quaternion from the passed rotation matrix values.
  4424. * Returns the updated Quaternion.
  4425. */
  4426. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4427. Quaternion.FromRotationMatrixToRef(matrix, this);
  4428. return this;
  4429. };
  4430. // Statics
  4431. /**
  4432. * Returns a new Quaternion set from the passed rotation matrix values.
  4433. */
  4434. Quaternion.FromRotationMatrix = function (matrix) {
  4435. var result = new Quaternion();
  4436. Quaternion.FromRotationMatrixToRef(matrix, result);
  4437. return result;
  4438. };
  4439. /**
  4440. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4441. */
  4442. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4443. var data = matrix.m;
  4444. var m11 = data[0], m12 = data[4], m13 = data[8];
  4445. var m21 = data[1], m22 = data[5], m23 = data[9];
  4446. var m31 = data[2], m32 = data[6], m33 = data[10];
  4447. var trace = m11 + m22 + m33;
  4448. var s;
  4449. if (trace > 0) {
  4450. s = 0.5 / Math.sqrt(trace + 1.0);
  4451. result.w = 0.25 / s;
  4452. result.x = (m32 - m23) * s;
  4453. result.y = (m13 - m31) * s;
  4454. result.z = (m21 - m12) * s;
  4455. }
  4456. else if (m11 > m22 && m11 > m33) {
  4457. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4458. result.w = (m32 - m23) / s;
  4459. result.x = 0.25 * s;
  4460. result.y = (m12 + m21) / s;
  4461. result.z = (m13 + m31) / s;
  4462. }
  4463. else if (m22 > m33) {
  4464. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4465. result.w = (m13 - m31) / s;
  4466. result.x = (m12 + m21) / s;
  4467. result.y = 0.25 * s;
  4468. result.z = (m23 + m32) / s;
  4469. }
  4470. else {
  4471. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4472. result.w = (m21 - m12) / s;
  4473. result.x = (m13 + m31) / s;
  4474. result.y = (m23 + m32) / s;
  4475. result.z = 0.25 * s;
  4476. }
  4477. };
  4478. /**
  4479. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4480. */
  4481. Quaternion.Zero = function () {
  4482. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4483. };
  4484. /**
  4485. * Returns a new Quaternion as the inverted current Quaternion.
  4486. */
  4487. Quaternion.Inverse = function (q) {
  4488. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4489. };
  4490. /**
  4491. * Returns the identity Quaternion.
  4492. */
  4493. Quaternion.Identity = function () {
  4494. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4495. };
  4496. Quaternion.IsIdentity = function (quaternion) {
  4497. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4498. };
  4499. /**
  4500. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4501. */
  4502. Quaternion.RotationAxis = function (axis, angle) {
  4503. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4504. };
  4505. /**
  4506. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4507. */
  4508. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4509. var sin = Math.sin(angle / 2);
  4510. axis.normalize();
  4511. result.w = Math.cos(angle / 2);
  4512. result.x = axis.x * sin;
  4513. result.y = axis.y * sin;
  4514. result.z = axis.z * sin;
  4515. return result;
  4516. };
  4517. /**
  4518. * Retuns a new Quaternion set from the starting index of the passed array.
  4519. */
  4520. Quaternion.FromArray = function (array, offset) {
  4521. if (!offset) {
  4522. offset = 0;
  4523. }
  4524. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4525. };
  4526. /**
  4527. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4528. */
  4529. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4530. var q = new Quaternion();
  4531. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4532. return q;
  4533. };
  4534. /**
  4535. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4536. */
  4537. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4538. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4539. var halfRoll = roll * 0.5;
  4540. var halfPitch = pitch * 0.5;
  4541. var halfYaw = yaw * 0.5;
  4542. var sinRoll = Math.sin(halfRoll);
  4543. var cosRoll = Math.cos(halfRoll);
  4544. var sinPitch = Math.sin(halfPitch);
  4545. var cosPitch = Math.cos(halfPitch);
  4546. var sinYaw = Math.sin(halfYaw);
  4547. var cosYaw = Math.cos(halfYaw);
  4548. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4549. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4550. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4551. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4552. };
  4553. /**
  4554. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4555. */
  4556. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4557. var result = new Quaternion();
  4558. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4559. return result;
  4560. };
  4561. /**
  4562. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4563. */
  4564. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4565. // Produces a quaternion from Euler angles in the z-x-z orientation
  4566. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4567. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4568. var halfBeta = beta * 0.5;
  4569. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4570. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4571. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4572. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4573. };
  4574. /**
  4575. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4576. * cf to Vector3.RotationFromAxis() documentation.
  4577. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4578. */
  4579. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4580. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4581. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4582. return quat;
  4583. };
  4584. /**
  4585. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4586. * cf to Vector3.RotationFromAxis() documentation.
  4587. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4588. */
  4589. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4590. var rotMat = MathTmp.Matrix[0];
  4591. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4592. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4593. };
  4594. Quaternion.Slerp = function (left, right, amount) {
  4595. var result = Quaternion.Identity();
  4596. Quaternion.SlerpToRef(left, right, amount, result);
  4597. return result;
  4598. };
  4599. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4600. var num2;
  4601. var num3;
  4602. var num = amount;
  4603. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4604. var flag = false;
  4605. if (num4 < 0) {
  4606. flag = true;
  4607. num4 = -num4;
  4608. }
  4609. if (num4 > 0.999999) {
  4610. num3 = 1 - num;
  4611. num2 = flag ? -num : num;
  4612. }
  4613. else {
  4614. var num5 = Math.acos(num4);
  4615. var num6 = (1.0 / Math.sin(num5));
  4616. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4617. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4618. }
  4619. result.x = (num3 * left.x) + (num2 * right.x);
  4620. result.y = (num3 * left.y) + (num2 * right.y);
  4621. result.z = (num3 * left.z) + (num2 * right.z);
  4622. result.w = (num3 * left.w) + (num2 * right.w);
  4623. };
  4624. /**
  4625. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4626. */
  4627. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4628. var squared = amount * amount;
  4629. var cubed = amount * squared;
  4630. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4631. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4632. var part3 = (cubed - (2.0 * squared)) + amount;
  4633. var part4 = cubed - squared;
  4634. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4635. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4636. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4637. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4638. return new Quaternion(x, y, z, w);
  4639. };
  4640. return Quaternion;
  4641. }());
  4642. BABYLON.Quaternion = Quaternion;
  4643. var Matrix = /** @class */ (function () {
  4644. function Matrix() {
  4645. this._isIdentity = false;
  4646. this._isIdentityDirty = true;
  4647. this.m = new Float32Array(16);
  4648. this._markAsUpdated();
  4649. }
  4650. Matrix.prototype._markAsUpdated = function () {
  4651. this.updateFlag = Matrix._updateFlagSeed++;
  4652. this._isIdentityDirty = true;
  4653. };
  4654. // Properties
  4655. /**
  4656. * Boolean : True is the matrix is the identity matrix
  4657. */
  4658. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4659. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4660. if (this._isIdentityDirty) {
  4661. this._isIdentityDirty = false;
  4662. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4663. this._isIdentity = false;
  4664. }
  4665. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4666. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4667. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4668. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4669. this._isIdentity = false;
  4670. }
  4671. else {
  4672. this._isIdentity = true;
  4673. }
  4674. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4675. this._isIdentity = false;
  4676. }
  4677. }
  4678. return this._isIdentity;
  4679. };
  4680. /**
  4681. * Returns the matrix determinant (float).
  4682. */
  4683. Matrix.prototype.determinant = function () {
  4684. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4685. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4686. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4687. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4688. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4689. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4690. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4691. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4692. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4693. };
  4694. // Methods
  4695. /**
  4696. * Returns the matrix underlying array.
  4697. */
  4698. Matrix.prototype.toArray = function () {
  4699. return this.m;
  4700. };
  4701. /**
  4702. * Returns the matrix underlying array.
  4703. */
  4704. Matrix.prototype.asArray = function () {
  4705. return this.toArray();
  4706. };
  4707. /**
  4708. * Inverts in place the Matrix.
  4709. * Returns the Matrix inverted.
  4710. */
  4711. Matrix.prototype.invert = function () {
  4712. this.invertToRef(this);
  4713. return this;
  4714. };
  4715. /**
  4716. * Sets all the matrix elements to zero.
  4717. * Returns the Matrix.
  4718. */
  4719. Matrix.prototype.reset = function () {
  4720. for (var index = 0; index < 16; index++) {
  4721. this.m[index] = 0.0;
  4722. }
  4723. this._markAsUpdated();
  4724. return this;
  4725. };
  4726. /**
  4727. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4728. */
  4729. Matrix.prototype.add = function (other) {
  4730. var result = new Matrix();
  4731. this.addToRef(other, result);
  4732. return result;
  4733. };
  4734. /**
  4735. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4736. * Returns the Matrix.
  4737. */
  4738. Matrix.prototype.addToRef = function (other, result) {
  4739. for (var index = 0; index < 16; index++) {
  4740. result.m[index] = this.m[index] + other.m[index];
  4741. }
  4742. result._markAsUpdated();
  4743. return this;
  4744. };
  4745. /**
  4746. * Adds in place the passed matrix to the current Matrix.
  4747. * Returns the updated Matrix.
  4748. */
  4749. Matrix.prototype.addToSelf = function (other) {
  4750. for (var index = 0; index < 16; index++) {
  4751. this.m[index] += other.m[index];
  4752. }
  4753. this._markAsUpdated();
  4754. return this;
  4755. };
  4756. /**
  4757. * Sets the passed matrix with the current inverted Matrix.
  4758. * Returns the unmodified current Matrix.
  4759. */
  4760. Matrix.prototype.invertToRef = function (other) {
  4761. var l1 = this.m[0];
  4762. var l2 = this.m[1];
  4763. var l3 = this.m[2];
  4764. var l4 = this.m[3];
  4765. var l5 = this.m[4];
  4766. var l6 = this.m[5];
  4767. var l7 = this.m[6];
  4768. var l8 = this.m[7];
  4769. var l9 = this.m[8];
  4770. var l10 = this.m[9];
  4771. var l11 = this.m[10];
  4772. var l12 = this.m[11];
  4773. var l13 = this.m[12];
  4774. var l14 = this.m[13];
  4775. var l15 = this.m[14];
  4776. var l16 = this.m[15];
  4777. var l17 = (l11 * l16) - (l12 * l15);
  4778. var l18 = (l10 * l16) - (l12 * l14);
  4779. var l19 = (l10 * l15) - (l11 * l14);
  4780. var l20 = (l9 * l16) - (l12 * l13);
  4781. var l21 = (l9 * l15) - (l11 * l13);
  4782. var l22 = (l9 * l14) - (l10 * l13);
  4783. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4784. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4785. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4786. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4787. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4788. var l28 = (l7 * l16) - (l8 * l15);
  4789. var l29 = (l6 * l16) - (l8 * l14);
  4790. var l30 = (l6 * l15) - (l7 * l14);
  4791. var l31 = (l5 * l16) - (l8 * l13);
  4792. var l32 = (l5 * l15) - (l7 * l13);
  4793. var l33 = (l5 * l14) - (l6 * l13);
  4794. var l34 = (l7 * l12) - (l8 * l11);
  4795. var l35 = (l6 * l12) - (l8 * l10);
  4796. var l36 = (l6 * l11) - (l7 * l10);
  4797. var l37 = (l5 * l12) - (l8 * l9);
  4798. var l38 = (l5 * l11) - (l7 * l9);
  4799. var l39 = (l5 * l10) - (l6 * l9);
  4800. other.m[0] = l23 * l27;
  4801. other.m[4] = l24 * l27;
  4802. other.m[8] = l25 * l27;
  4803. other.m[12] = l26 * l27;
  4804. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4805. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4806. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4807. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4808. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4809. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4810. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4811. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4812. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4813. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4814. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4815. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4816. other._markAsUpdated();
  4817. return this;
  4818. };
  4819. /**
  4820. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4821. * Returns the updated Matrix.
  4822. */
  4823. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4824. this.m[12] = x;
  4825. this.m[13] = y;
  4826. this.m[14] = z;
  4827. this._markAsUpdated();
  4828. return this;
  4829. };
  4830. /**
  4831. * Inserts the translation vector in the current Matrix.
  4832. * Returns the updated Matrix.
  4833. */
  4834. Matrix.prototype.setTranslation = function (vector3) {
  4835. this.m[12] = vector3.x;
  4836. this.m[13] = vector3.y;
  4837. this.m[14] = vector3.z;
  4838. this._markAsUpdated();
  4839. return this;
  4840. };
  4841. /**
  4842. * Returns a new Vector3 as the extracted translation from the Matrix.
  4843. */
  4844. Matrix.prototype.getTranslation = function () {
  4845. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4846. };
  4847. /**
  4848. * Fill a Vector3 with the extracted translation from the Matrix.
  4849. */
  4850. Matrix.prototype.getTranslationToRef = function (result) {
  4851. result.x = this.m[12];
  4852. result.y = this.m[13];
  4853. result.z = this.m[14];
  4854. return this;
  4855. };
  4856. /**
  4857. * Remove rotation and scaling part from the Matrix.
  4858. * Returns the updated Matrix.
  4859. */
  4860. Matrix.prototype.removeRotationAndScaling = function () {
  4861. this.setRowFromFloats(0, 1, 0, 0, 0);
  4862. this.setRowFromFloats(1, 0, 1, 0, 0);
  4863. this.setRowFromFloats(2, 0, 0, 1, 0);
  4864. return this;
  4865. };
  4866. /**
  4867. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4868. */
  4869. Matrix.prototype.multiply = function (other) {
  4870. var result = new Matrix();
  4871. this.multiplyToRef(other, result);
  4872. return result;
  4873. };
  4874. /**
  4875. * Updates the current Matrix from the passed one values.
  4876. * Returns the updated Matrix.
  4877. */
  4878. Matrix.prototype.copyFrom = function (other) {
  4879. for (var index = 0; index < 16; index++) {
  4880. this.m[index] = other.m[index];
  4881. }
  4882. this._markAsUpdated();
  4883. return this;
  4884. };
  4885. /**
  4886. * Populates the passed array from the starting index with the Matrix values.
  4887. * Returns the Matrix.
  4888. */
  4889. Matrix.prototype.copyToArray = function (array, offset) {
  4890. if (offset === void 0) { offset = 0; }
  4891. for (var index = 0; index < 16; index++) {
  4892. array[offset + index] = this.m[index];
  4893. }
  4894. return this;
  4895. };
  4896. /**
  4897. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4898. */
  4899. Matrix.prototype.multiplyToRef = function (other, result) {
  4900. this.multiplyToArray(other, result.m, 0);
  4901. result._markAsUpdated();
  4902. return this;
  4903. };
  4904. /**
  4905. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4906. */
  4907. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4908. var tm0 = this.m[0];
  4909. var tm1 = this.m[1];
  4910. var tm2 = this.m[2];
  4911. var tm3 = this.m[3];
  4912. var tm4 = this.m[4];
  4913. var tm5 = this.m[5];
  4914. var tm6 = this.m[6];
  4915. var tm7 = this.m[7];
  4916. var tm8 = this.m[8];
  4917. var tm9 = this.m[9];
  4918. var tm10 = this.m[10];
  4919. var tm11 = this.m[11];
  4920. var tm12 = this.m[12];
  4921. var tm13 = this.m[13];
  4922. var tm14 = this.m[14];
  4923. var tm15 = this.m[15];
  4924. var om0 = other.m[0];
  4925. var om1 = other.m[1];
  4926. var om2 = other.m[2];
  4927. var om3 = other.m[3];
  4928. var om4 = other.m[4];
  4929. var om5 = other.m[5];
  4930. var om6 = other.m[6];
  4931. var om7 = other.m[7];
  4932. var om8 = other.m[8];
  4933. var om9 = other.m[9];
  4934. var om10 = other.m[10];
  4935. var om11 = other.m[11];
  4936. var om12 = other.m[12];
  4937. var om13 = other.m[13];
  4938. var om14 = other.m[14];
  4939. var om15 = other.m[15];
  4940. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4941. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4942. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4943. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4944. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4945. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4946. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4947. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4948. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4949. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4950. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4951. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4952. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4953. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4954. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4955. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4956. return this;
  4957. };
  4958. /**
  4959. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4960. */
  4961. Matrix.prototype.equals = function (value) {
  4962. return value &&
  4963. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4964. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4965. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4966. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4967. };
  4968. /**
  4969. * Returns a new Matrix from the current Matrix.
  4970. */
  4971. Matrix.prototype.clone = function () {
  4972. 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]);
  4973. };
  4974. /**
  4975. * Returns the string "Matrix"
  4976. */
  4977. Matrix.prototype.getClassName = function () {
  4978. return "Matrix";
  4979. };
  4980. /**
  4981. * Returns the Matrix hash code.
  4982. */
  4983. Matrix.prototype.getHashCode = function () {
  4984. var hash = this.m[0] || 0;
  4985. for (var i = 1; i < 16; i++) {
  4986. hash = (hash * 397) ^ (this.m[i] || 0);
  4987. }
  4988. return hash;
  4989. };
  4990. /**
  4991. * Decomposes the current Matrix into :
  4992. * - a scale vector3 passed as a reference to update,
  4993. * - a rotation quaternion passed as a reference to update,
  4994. * - a translation vector3 passed as a reference to update.
  4995. * Returns the true if operation was successful.
  4996. */
  4997. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4998. translation.x = this.m[12];
  4999. translation.y = this.m[13];
  5000. translation.z = this.m[14];
  5001. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5002. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5003. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5004. if (this.determinant() <= 0) {
  5005. scale.y *= -1;
  5006. }
  5007. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5008. rotation.x = 0;
  5009. rotation.y = 0;
  5010. rotation.z = 0;
  5011. rotation.w = 1;
  5012. return false;
  5013. }
  5014. 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]);
  5015. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5016. return true;
  5017. };
  5018. /**
  5019. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5020. * @param ref matrix to store the result
  5021. */
  5022. Matrix.prototype.toNormalMatrix = function (ref) {
  5023. this.invertToRef(ref);
  5024. ref.transpose();
  5025. var m = ref.m;
  5026. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5027. };
  5028. /**
  5029. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5030. */
  5031. Matrix.prototype.getRotationMatrix = function () {
  5032. var result = Matrix.Identity();
  5033. this.getRotationMatrixToRef(result);
  5034. return result;
  5035. };
  5036. /**
  5037. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5038. * Returns the current Matrix.
  5039. */
  5040. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5041. var m = this.m;
  5042. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5043. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5044. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5045. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5046. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5047. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5048. 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);
  5049. return this;
  5050. };
  5051. // Statics
  5052. /**
  5053. * Returns a new Matrix set from the starting index of the passed array.
  5054. */
  5055. Matrix.FromArray = function (array, offset) {
  5056. var result = new Matrix();
  5057. if (!offset) {
  5058. offset = 0;
  5059. }
  5060. Matrix.FromArrayToRef(array, offset, result);
  5061. return result;
  5062. };
  5063. /**
  5064. * Sets the passed "result" matrix from the starting index of the passed array.
  5065. */
  5066. Matrix.FromArrayToRef = function (array, offset, result) {
  5067. for (var index = 0; index < 16; index++) {
  5068. result.m[index] = array[index + offset];
  5069. }
  5070. result._markAsUpdated();
  5071. };
  5072. /**
  5073. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5074. */
  5075. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5076. for (var index = 0; index < 16; index++) {
  5077. result.m[index] = array[index + offset] * scale;
  5078. }
  5079. result._markAsUpdated();
  5080. };
  5081. /**
  5082. * Sets the passed matrix "result" with the 16 passed floats.
  5083. */
  5084. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5085. result.m[0] = initialM11;
  5086. result.m[1] = initialM12;
  5087. result.m[2] = initialM13;
  5088. result.m[3] = initialM14;
  5089. result.m[4] = initialM21;
  5090. result.m[5] = initialM22;
  5091. result.m[6] = initialM23;
  5092. result.m[7] = initialM24;
  5093. result.m[8] = initialM31;
  5094. result.m[9] = initialM32;
  5095. result.m[10] = initialM33;
  5096. result.m[11] = initialM34;
  5097. result.m[12] = initialM41;
  5098. result.m[13] = initialM42;
  5099. result.m[14] = initialM43;
  5100. result.m[15] = initialM44;
  5101. result._markAsUpdated();
  5102. };
  5103. /**
  5104. * Returns the index-th row of the current matrix as a new Vector4.
  5105. */
  5106. Matrix.prototype.getRow = function (index) {
  5107. if (index < 0 || index > 3) {
  5108. return null;
  5109. }
  5110. var i = index * 4;
  5111. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5112. };
  5113. /**
  5114. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5115. * Returns the updated Matrix.
  5116. */
  5117. Matrix.prototype.setRow = function (index, row) {
  5118. if (index < 0 || index > 3) {
  5119. return this;
  5120. }
  5121. var i = index * 4;
  5122. this.m[i + 0] = row.x;
  5123. this.m[i + 1] = row.y;
  5124. this.m[i + 2] = row.z;
  5125. this.m[i + 3] = row.w;
  5126. this._markAsUpdated();
  5127. return this;
  5128. };
  5129. /**
  5130. * Compute the transpose of the matrix.
  5131. * Returns a new Matrix.
  5132. */
  5133. Matrix.prototype.transpose = function () {
  5134. return Matrix.Transpose(this);
  5135. };
  5136. /**
  5137. * Compute the transpose of the matrix.
  5138. * Returns the current matrix.
  5139. */
  5140. Matrix.prototype.transposeToRef = function (result) {
  5141. Matrix.TransposeToRef(this, result);
  5142. return this;
  5143. };
  5144. /**
  5145. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5146. * Returns the updated Matrix.
  5147. */
  5148. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5149. if (index < 0 || index > 3) {
  5150. return this;
  5151. }
  5152. var i = index * 4;
  5153. this.m[i + 0] = x;
  5154. this.m[i + 1] = y;
  5155. this.m[i + 2] = z;
  5156. this.m[i + 3] = w;
  5157. this._markAsUpdated();
  5158. return this;
  5159. };
  5160. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5161. /**
  5162. * Static identity matrix to be used as readonly matrix
  5163. * Must not be updated.
  5164. */
  5165. get: function () {
  5166. return Matrix._identityReadOnly;
  5167. },
  5168. enumerable: true,
  5169. configurable: true
  5170. });
  5171. /**
  5172. * Returns a new Matrix set from the 16 passed floats.
  5173. */
  5174. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5175. var result = new Matrix();
  5176. result.m[0] = initialM11;
  5177. result.m[1] = initialM12;
  5178. result.m[2] = initialM13;
  5179. result.m[3] = initialM14;
  5180. result.m[4] = initialM21;
  5181. result.m[5] = initialM22;
  5182. result.m[6] = initialM23;
  5183. result.m[7] = initialM24;
  5184. result.m[8] = initialM31;
  5185. result.m[9] = initialM32;
  5186. result.m[10] = initialM33;
  5187. result.m[11] = initialM34;
  5188. result.m[12] = initialM41;
  5189. result.m[13] = initialM42;
  5190. result.m[14] = initialM43;
  5191. result.m[15] = initialM44;
  5192. return result;
  5193. };
  5194. /**
  5195. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5196. */
  5197. Matrix.Compose = function (scale, rotation, translation) {
  5198. var result = Matrix.Identity();
  5199. Matrix.ComposeToRef(scale, rotation, translation, result);
  5200. return result;
  5201. };
  5202. /**
  5203. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5204. */
  5205. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5206. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5207. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5208. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5209. result.setTranslation(translation);
  5210. };
  5211. /**
  5212. * Returns a new indentity Matrix.
  5213. */
  5214. Matrix.Identity = function () {
  5215. 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);
  5216. };
  5217. /**
  5218. * Sets the passed "result" as an identity matrix.
  5219. */
  5220. Matrix.IdentityToRef = function (result) {
  5221. 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);
  5222. };
  5223. /**
  5224. * Returns a new zero Matrix.
  5225. */
  5226. Matrix.Zero = function () {
  5227. 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);
  5228. };
  5229. /**
  5230. * Returns a new rotation matrix for "angle" radians around the X axis.
  5231. */
  5232. Matrix.RotationX = function (angle) {
  5233. var result = new Matrix();
  5234. Matrix.RotationXToRef(angle, result);
  5235. return result;
  5236. };
  5237. /**
  5238. * Returns a new Matrix as the passed inverted one.
  5239. */
  5240. Matrix.Invert = function (source) {
  5241. var result = new Matrix();
  5242. source.invertToRef(result);
  5243. return result;
  5244. };
  5245. /**
  5246. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5247. */
  5248. Matrix.RotationXToRef = function (angle, result) {
  5249. var s = Math.sin(angle);
  5250. var c = Math.cos(angle);
  5251. result.m[0] = 1.0;
  5252. result.m[15] = 1.0;
  5253. result.m[5] = c;
  5254. result.m[10] = c;
  5255. result.m[9] = -s;
  5256. result.m[6] = s;
  5257. result.m[1] = 0.0;
  5258. result.m[2] = 0.0;
  5259. result.m[3] = 0.0;
  5260. result.m[4] = 0.0;
  5261. result.m[7] = 0.0;
  5262. result.m[8] = 0.0;
  5263. result.m[11] = 0.0;
  5264. result.m[12] = 0.0;
  5265. result.m[13] = 0.0;
  5266. result.m[14] = 0.0;
  5267. result._markAsUpdated();
  5268. };
  5269. /**
  5270. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5271. */
  5272. Matrix.RotationY = function (angle) {
  5273. var result = new Matrix();
  5274. Matrix.RotationYToRef(angle, result);
  5275. return result;
  5276. };
  5277. /**
  5278. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5279. */
  5280. Matrix.RotationYToRef = function (angle, result) {
  5281. var s = Math.sin(angle);
  5282. var c = Math.cos(angle);
  5283. result.m[5] = 1.0;
  5284. result.m[15] = 1.0;
  5285. result.m[0] = c;
  5286. result.m[2] = -s;
  5287. result.m[8] = s;
  5288. result.m[10] = c;
  5289. result.m[1] = 0.0;
  5290. result.m[3] = 0.0;
  5291. result.m[4] = 0.0;
  5292. result.m[6] = 0.0;
  5293. result.m[7] = 0.0;
  5294. result.m[9] = 0.0;
  5295. result.m[11] = 0.0;
  5296. result.m[12] = 0.0;
  5297. result.m[13] = 0.0;
  5298. result.m[14] = 0.0;
  5299. result._markAsUpdated();
  5300. };
  5301. /**
  5302. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5303. */
  5304. Matrix.RotationZ = function (angle) {
  5305. var result = new Matrix();
  5306. Matrix.RotationZToRef(angle, result);
  5307. return result;
  5308. };
  5309. /**
  5310. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5311. */
  5312. Matrix.RotationZToRef = function (angle, result) {
  5313. var s = Math.sin(angle);
  5314. var c = Math.cos(angle);
  5315. result.m[10] = 1.0;
  5316. result.m[15] = 1.0;
  5317. result.m[0] = c;
  5318. result.m[1] = s;
  5319. result.m[4] = -s;
  5320. result.m[5] = c;
  5321. result.m[2] = 0.0;
  5322. result.m[3] = 0.0;
  5323. result.m[6] = 0.0;
  5324. result.m[7] = 0.0;
  5325. result.m[8] = 0.0;
  5326. result.m[9] = 0.0;
  5327. result.m[11] = 0.0;
  5328. result.m[12] = 0.0;
  5329. result.m[13] = 0.0;
  5330. result.m[14] = 0.0;
  5331. result._markAsUpdated();
  5332. };
  5333. /**
  5334. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5335. */
  5336. Matrix.RotationAxis = function (axis, angle) {
  5337. var result = Matrix.Zero();
  5338. Matrix.RotationAxisToRef(axis, angle, result);
  5339. return result;
  5340. };
  5341. /**
  5342. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5343. */
  5344. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5345. var s = Math.sin(-angle);
  5346. var c = Math.cos(-angle);
  5347. var c1 = 1 - c;
  5348. axis.normalize();
  5349. result.m[0] = (axis.x * axis.x) * c1 + c;
  5350. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5351. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5352. result.m[3] = 0.0;
  5353. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5354. result.m[5] = (axis.y * axis.y) * c1 + c;
  5355. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5356. result.m[7] = 0.0;
  5357. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5358. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5359. result.m[10] = (axis.z * axis.z) * c1 + c;
  5360. result.m[11] = 0.0;
  5361. result.m[15] = 1.0;
  5362. result._markAsUpdated();
  5363. };
  5364. /**
  5365. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5366. */
  5367. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5368. var result = new Matrix();
  5369. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5370. return result;
  5371. };
  5372. /**
  5373. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5374. */
  5375. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5376. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5377. this._tempQuaternion.toRotationMatrix(result);
  5378. };
  5379. /**
  5380. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5381. */
  5382. Matrix.Scaling = function (x, y, z) {
  5383. var result = Matrix.Zero();
  5384. Matrix.ScalingToRef(x, y, z, result);
  5385. return result;
  5386. };
  5387. /**
  5388. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5389. */
  5390. Matrix.ScalingToRef = function (x, y, z, result) {
  5391. result.m[0] = x;
  5392. result.m[1] = 0.0;
  5393. result.m[2] = 0.0;
  5394. result.m[3] = 0.0;
  5395. result.m[4] = 0.0;
  5396. result.m[5] = y;
  5397. result.m[6] = 0.0;
  5398. result.m[7] = 0.0;
  5399. result.m[8] = 0.0;
  5400. result.m[9] = 0.0;
  5401. result.m[10] = z;
  5402. result.m[11] = 0.0;
  5403. result.m[12] = 0.0;
  5404. result.m[13] = 0.0;
  5405. result.m[14] = 0.0;
  5406. result.m[15] = 1.0;
  5407. result._markAsUpdated();
  5408. };
  5409. /**
  5410. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5411. */
  5412. Matrix.Translation = function (x, y, z) {
  5413. var result = Matrix.Identity();
  5414. Matrix.TranslationToRef(x, y, z, result);
  5415. return result;
  5416. };
  5417. /**
  5418. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5419. */
  5420. Matrix.TranslationToRef = function (x, y, z, result) {
  5421. 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);
  5422. };
  5423. /**
  5424. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5425. * @param startValue defines the start value
  5426. * @param endValue defines the end value
  5427. * @param gradient defines the gradient factor
  5428. * @returns the new matrix
  5429. */
  5430. Matrix.Lerp = function (startValue, endValue, gradient) {
  5431. var result = Matrix.Zero();
  5432. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5433. return result;
  5434. };
  5435. /**
  5436. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5437. * @param startValue defines the start value
  5438. * @param endValue defines the end value
  5439. * @param gradient defines the gradient factor
  5440. * @param result defines the Matrix object where to store data
  5441. */
  5442. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5443. for (var index = 0; index < 16; index++) {
  5444. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5445. }
  5446. result._markAsUpdated();
  5447. };
  5448. /**
  5449. * Returns a new Matrix whose values are computed by :
  5450. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5451. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5452. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5453. */
  5454. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5455. var startScale = new Vector3(0, 0, 0);
  5456. var startRotation = new Quaternion();
  5457. var startTranslation = new Vector3(0, 0, 0);
  5458. startValue.decompose(startScale, startRotation, startTranslation);
  5459. var endScale = new Vector3(0, 0, 0);
  5460. var endRotation = new Quaternion();
  5461. var endTranslation = new Vector3(0, 0, 0);
  5462. endValue.decompose(endScale, endRotation, endTranslation);
  5463. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5464. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5465. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5466. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5467. };
  5468. /**
  5469. * 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".
  5470. * This methods works for a Left-Handed system.
  5471. */
  5472. Matrix.LookAtLH = function (eye, target, up) {
  5473. var result = Matrix.Zero();
  5474. Matrix.LookAtLHToRef(eye, target, up, result);
  5475. return result;
  5476. };
  5477. /**
  5478. * 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".
  5479. * This methods works for a Left-Handed system.
  5480. */
  5481. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5482. // Z axis
  5483. target.subtractToRef(eye, this._zAxis);
  5484. this._zAxis.normalize();
  5485. // X axis
  5486. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5487. if (this._xAxis.lengthSquared() === 0) {
  5488. this._xAxis.x = 1.0;
  5489. }
  5490. else {
  5491. this._xAxis.normalize();
  5492. }
  5493. // Y axis
  5494. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5495. this._yAxis.normalize();
  5496. // Eye angles
  5497. var ex = -Vector3.Dot(this._xAxis, eye);
  5498. var ey = -Vector3.Dot(this._yAxis, eye);
  5499. var ez = -Vector3.Dot(this._zAxis, eye);
  5500. 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);
  5501. };
  5502. /**
  5503. * 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".
  5504. * This methods works for a Right-Handed system.
  5505. */
  5506. Matrix.LookAtRH = function (eye, target, up) {
  5507. var result = Matrix.Zero();
  5508. Matrix.LookAtRHToRef(eye, target, up, result);
  5509. return result;
  5510. };
  5511. /**
  5512. * 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".
  5513. * This methods works for a Left-Handed system.
  5514. */
  5515. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5516. // Z axis
  5517. eye.subtractToRef(target, this._zAxis);
  5518. this._zAxis.normalize();
  5519. // X axis
  5520. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5521. if (this._xAxis.lengthSquared() === 0) {
  5522. this._xAxis.x = 1.0;
  5523. }
  5524. else {
  5525. this._xAxis.normalize();
  5526. }
  5527. // Y axis
  5528. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5529. this._yAxis.normalize();
  5530. // Eye angles
  5531. var ex = -Vector3.Dot(this._xAxis, eye);
  5532. var ey = -Vector3.Dot(this._yAxis, eye);
  5533. var ez = -Vector3.Dot(this._zAxis, eye);
  5534. 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);
  5535. };
  5536. /**
  5537. * 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.
  5538. */
  5539. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5540. var matrix = Matrix.Zero();
  5541. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5542. return matrix;
  5543. };
  5544. /**
  5545. * 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.
  5546. */
  5547. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5548. var n = znear;
  5549. var f = zfar;
  5550. var a = 2.0 / width;
  5551. var b = 2.0 / height;
  5552. var c = 2.0 / (f - n);
  5553. var d = -(f + n) / (f - n);
  5554. 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);
  5555. };
  5556. /**
  5557. * 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.
  5558. */
  5559. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5560. var matrix = Matrix.Zero();
  5561. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5562. return matrix;
  5563. };
  5564. /**
  5565. * 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.
  5566. */
  5567. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5568. var n = znear;
  5569. var f = zfar;
  5570. var a = 2.0 / (right - left);
  5571. var b = 2.0 / (top - bottom);
  5572. var c = 2.0 / (f - n);
  5573. var d = -(f + n) / (f - n);
  5574. var i0 = (left + right) / (left - right);
  5575. var i1 = (top + bottom) / (bottom - top);
  5576. 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);
  5577. };
  5578. /**
  5579. * 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.
  5580. */
  5581. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5582. var matrix = Matrix.Zero();
  5583. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5584. return matrix;
  5585. };
  5586. /**
  5587. * 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.
  5588. */
  5589. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5590. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5591. result.m[10] *= -1.0;
  5592. };
  5593. /**
  5594. * 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.
  5595. */
  5596. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5597. var matrix = Matrix.Zero();
  5598. var n = znear;
  5599. var f = zfar;
  5600. var a = 2.0 * n / width;
  5601. var b = 2.0 * n / height;
  5602. var c = (f + n) / (f - n);
  5603. var d = -2.0 * f * n / (f - n);
  5604. 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);
  5605. return matrix;
  5606. };
  5607. /**
  5608. * 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.
  5609. */
  5610. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5611. var matrix = Matrix.Zero();
  5612. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5613. return matrix;
  5614. };
  5615. /**
  5616. * 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.
  5617. */
  5618. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5619. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5620. var n = znear;
  5621. var f = zfar;
  5622. var t = 1.0 / (Math.tan(fov * 0.5));
  5623. var a = isVerticalFovFixed ? (t / aspect) : t;
  5624. var b = isVerticalFovFixed ? t : (t * aspect);
  5625. var c = (f + n) / (f - n);
  5626. var d = -2.0 * f * n / (f - n);
  5627. 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);
  5628. };
  5629. /**
  5630. * 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.
  5631. */
  5632. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5633. var matrix = Matrix.Zero();
  5634. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5635. return matrix;
  5636. };
  5637. /**
  5638. * 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.
  5639. */
  5640. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5641. //alternatively this could be expressed as:
  5642. // m = PerspectiveFovLHToRef
  5643. // m[10] *= -1.0;
  5644. // m[11] *= -1.0;
  5645. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5646. var n = znear;
  5647. var f = zfar;
  5648. var t = 1.0 / (Math.tan(fov * 0.5));
  5649. var a = isVerticalFovFixed ? (t / aspect) : t;
  5650. var b = isVerticalFovFixed ? t : (t * aspect);
  5651. var c = -(f + n) / (f - n);
  5652. var d = -2 * f * n / (f - n);
  5653. 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);
  5654. };
  5655. /**
  5656. * 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.
  5657. */
  5658. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5659. if (rightHanded === void 0) { rightHanded = false; }
  5660. var rightHandedFactor = rightHanded ? -1 : 1;
  5661. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5662. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5663. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5664. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5665. var xScale = 2.0 / (leftTan + rightTan);
  5666. var yScale = 2.0 / (upTan + downTan);
  5667. result.m[0] = xScale;
  5668. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5669. result.m[5] = yScale;
  5670. result.m[6] = result.m[7] = 0.0;
  5671. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5672. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5673. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5674. result.m[10] = -zfar / (znear - zfar);
  5675. result.m[11] = 1.0 * rightHandedFactor;
  5676. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5677. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5678. // result.m[14] = (znear * zfar) / (znear - zfar);
  5679. result._markAsUpdated();
  5680. };
  5681. /**
  5682. * Returns the final transformation matrix : world * view * projection * viewport
  5683. */
  5684. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5685. var cw = viewport.width;
  5686. var ch = viewport.height;
  5687. var cx = viewport.x;
  5688. var cy = viewport.y;
  5689. 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);
  5690. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5691. };
  5692. /**
  5693. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5694. */
  5695. Matrix.GetAsMatrix2x2 = function (matrix) {
  5696. return new Float32Array([
  5697. matrix.m[0], matrix.m[1],
  5698. matrix.m[4], matrix.m[5]
  5699. ]);
  5700. };
  5701. /**
  5702. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5703. */
  5704. Matrix.GetAsMatrix3x3 = function (matrix) {
  5705. return new Float32Array([
  5706. matrix.m[0], matrix.m[1], matrix.m[2],
  5707. matrix.m[4], matrix.m[5], matrix.m[6],
  5708. matrix.m[8], matrix.m[9], matrix.m[10]
  5709. ]);
  5710. };
  5711. /**
  5712. * Compute the transpose of the passed Matrix.
  5713. * Returns a new Matrix.
  5714. */
  5715. Matrix.Transpose = function (matrix) {
  5716. var result = new Matrix();
  5717. Matrix.TransposeToRef(matrix, result);
  5718. return result;
  5719. };
  5720. /**
  5721. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5722. */
  5723. Matrix.TransposeToRef = function (matrix, result) {
  5724. result.m[0] = matrix.m[0];
  5725. result.m[1] = matrix.m[4];
  5726. result.m[2] = matrix.m[8];
  5727. result.m[3] = matrix.m[12];
  5728. result.m[4] = matrix.m[1];
  5729. result.m[5] = matrix.m[5];
  5730. result.m[6] = matrix.m[9];
  5731. result.m[7] = matrix.m[13];
  5732. result.m[8] = matrix.m[2];
  5733. result.m[9] = matrix.m[6];
  5734. result.m[10] = matrix.m[10];
  5735. result.m[11] = matrix.m[14];
  5736. result.m[12] = matrix.m[3];
  5737. result.m[13] = matrix.m[7];
  5738. result.m[14] = matrix.m[11];
  5739. result.m[15] = matrix.m[15];
  5740. };
  5741. /**
  5742. * Returns a new Matrix as the reflection matrix across the passed plane.
  5743. */
  5744. Matrix.Reflection = function (plane) {
  5745. var matrix = new Matrix();
  5746. Matrix.ReflectionToRef(plane, matrix);
  5747. return matrix;
  5748. };
  5749. /**
  5750. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5751. */
  5752. Matrix.ReflectionToRef = function (plane, result) {
  5753. plane.normalize();
  5754. var x = plane.normal.x;
  5755. var y = plane.normal.y;
  5756. var z = plane.normal.z;
  5757. var temp = -2 * x;
  5758. var temp2 = -2 * y;
  5759. var temp3 = -2 * z;
  5760. result.m[0] = (temp * x) + 1;
  5761. result.m[1] = temp2 * x;
  5762. result.m[2] = temp3 * x;
  5763. result.m[3] = 0.0;
  5764. result.m[4] = temp * y;
  5765. result.m[5] = (temp2 * y) + 1;
  5766. result.m[6] = temp3 * y;
  5767. result.m[7] = 0.0;
  5768. result.m[8] = temp * z;
  5769. result.m[9] = temp2 * z;
  5770. result.m[10] = (temp3 * z) + 1;
  5771. result.m[11] = 0.0;
  5772. result.m[12] = temp * plane.d;
  5773. result.m[13] = temp2 * plane.d;
  5774. result.m[14] = temp3 * plane.d;
  5775. result.m[15] = 1.0;
  5776. result._markAsUpdated();
  5777. };
  5778. /**
  5779. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5780. */
  5781. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5782. result.m[0] = xaxis.x;
  5783. result.m[1] = xaxis.y;
  5784. result.m[2] = xaxis.z;
  5785. result.m[3] = 0.0;
  5786. result.m[4] = yaxis.x;
  5787. result.m[5] = yaxis.y;
  5788. result.m[6] = yaxis.z;
  5789. result.m[7] = 0.0;
  5790. result.m[8] = zaxis.x;
  5791. result.m[9] = zaxis.y;
  5792. result.m[10] = zaxis.z;
  5793. result.m[11] = 0.0;
  5794. result.m[12] = 0.0;
  5795. result.m[13] = 0.0;
  5796. result.m[14] = 0.0;
  5797. result.m[15] = 1.0;
  5798. result._markAsUpdated();
  5799. };
  5800. /**
  5801. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5802. */
  5803. Matrix.FromQuaternionToRef = function (quat, result) {
  5804. var xx = quat.x * quat.x;
  5805. var yy = quat.y * quat.y;
  5806. var zz = quat.z * quat.z;
  5807. var xy = quat.x * quat.y;
  5808. var zw = quat.z * quat.w;
  5809. var zx = quat.z * quat.x;
  5810. var yw = quat.y * quat.w;
  5811. var yz = quat.y * quat.z;
  5812. var xw = quat.x * quat.w;
  5813. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5814. result.m[1] = 2.0 * (xy + zw);
  5815. result.m[2] = 2.0 * (zx - yw);
  5816. result.m[3] = 0.0;
  5817. result.m[4] = 2.0 * (xy - zw);
  5818. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5819. result.m[6] = 2.0 * (yz + xw);
  5820. result.m[7] = 0.0;
  5821. result.m[8] = 2.0 * (zx + yw);
  5822. result.m[9] = 2.0 * (yz - xw);
  5823. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5824. result.m[11] = 0.0;
  5825. result.m[12] = 0.0;
  5826. result.m[13] = 0.0;
  5827. result.m[14] = 0.0;
  5828. result.m[15] = 1.0;
  5829. result._markAsUpdated();
  5830. };
  5831. Matrix._tempQuaternion = new Quaternion();
  5832. Matrix._xAxis = Vector3.Zero();
  5833. Matrix._yAxis = Vector3.Zero();
  5834. Matrix._zAxis = Vector3.Zero();
  5835. Matrix._updateFlagSeed = 0;
  5836. Matrix._identityReadOnly = Matrix.Identity();
  5837. return Matrix;
  5838. }());
  5839. BABYLON.Matrix = Matrix;
  5840. var Plane = /** @class */ (function () {
  5841. /**
  5842. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5843. */
  5844. function Plane(a, b, c, d) {
  5845. this.normal = new Vector3(a, b, c);
  5846. this.d = d;
  5847. }
  5848. /**
  5849. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5850. */
  5851. Plane.prototype.asArray = function () {
  5852. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5853. };
  5854. // Methods
  5855. /**
  5856. * Returns a new plane copied from the current Plane.
  5857. */
  5858. Plane.prototype.clone = function () {
  5859. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5860. };
  5861. /**
  5862. * Returns the string "Plane".
  5863. */
  5864. Plane.prototype.getClassName = function () {
  5865. return "Plane";
  5866. };
  5867. /**
  5868. * Returns the Plane hash code.
  5869. */
  5870. Plane.prototype.getHashCode = function () {
  5871. var hash = this.normal.getHashCode();
  5872. hash = (hash * 397) ^ (this.d || 0);
  5873. return hash;
  5874. };
  5875. /**
  5876. * Normalize the current Plane in place.
  5877. * Returns the updated Plane.
  5878. */
  5879. Plane.prototype.normalize = function () {
  5880. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5881. var magnitude = 0.0;
  5882. if (norm !== 0) {
  5883. magnitude = 1.0 / norm;
  5884. }
  5885. this.normal.x *= magnitude;
  5886. this.normal.y *= magnitude;
  5887. this.normal.z *= magnitude;
  5888. this.d *= magnitude;
  5889. return this;
  5890. };
  5891. /**
  5892. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5893. */
  5894. Plane.prototype.transform = function (transformation) {
  5895. var transposedMatrix = Matrix.Transpose(transformation);
  5896. var x = this.normal.x;
  5897. var y = this.normal.y;
  5898. var z = this.normal.z;
  5899. var d = this.d;
  5900. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5901. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5902. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5903. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5904. return new Plane(normalX, normalY, normalZ, finalD);
  5905. };
  5906. /**
  5907. * Returns the dot product (float) of the point coordinates and the plane normal.
  5908. */
  5909. Plane.prototype.dotCoordinate = function (point) {
  5910. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5911. };
  5912. /**
  5913. * Updates the current Plane from the plane defined by the three passed points.
  5914. * Returns the updated Plane.
  5915. */
  5916. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5917. var x1 = point2.x - point1.x;
  5918. var y1 = point2.y - point1.y;
  5919. var z1 = point2.z - point1.z;
  5920. var x2 = point3.x - point1.x;
  5921. var y2 = point3.y - point1.y;
  5922. var z2 = point3.z - point1.z;
  5923. var yz = (y1 * z2) - (z1 * y2);
  5924. var xz = (z1 * x2) - (x1 * z2);
  5925. var xy = (x1 * y2) - (y1 * x2);
  5926. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5927. var invPyth;
  5928. if (pyth !== 0) {
  5929. invPyth = 1.0 / pyth;
  5930. }
  5931. else {
  5932. invPyth = 0.0;
  5933. }
  5934. this.normal.x = yz * invPyth;
  5935. this.normal.y = xz * invPyth;
  5936. this.normal.z = xy * invPyth;
  5937. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5938. return this;
  5939. };
  5940. /**
  5941. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5942. */
  5943. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5944. var dot = Vector3.Dot(this.normal, direction);
  5945. return (dot <= epsilon);
  5946. };
  5947. /**
  5948. * Returns the signed distance (float) from the passed point to the Plane.
  5949. */
  5950. Plane.prototype.signedDistanceTo = function (point) {
  5951. return Vector3.Dot(point, this.normal) + this.d;
  5952. };
  5953. // Statics
  5954. /**
  5955. * Returns a new Plane from the passed array.
  5956. */
  5957. Plane.FromArray = function (array) {
  5958. return new Plane(array[0], array[1], array[2], array[3]);
  5959. };
  5960. /**
  5961. * Returns a new Plane defined by the three passed points.
  5962. */
  5963. Plane.FromPoints = function (point1, point2, point3) {
  5964. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5965. result.copyFromPoints(point1, point2, point3);
  5966. return result;
  5967. };
  5968. /**
  5969. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5970. * Note : the vector "normal" is updated because normalized.
  5971. */
  5972. Plane.FromPositionAndNormal = function (origin, normal) {
  5973. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5974. normal.normalize();
  5975. result.normal = normal;
  5976. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5977. return result;
  5978. };
  5979. /**
  5980. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5981. */
  5982. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5983. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5984. return Vector3.Dot(point, normal) + d;
  5985. };
  5986. return Plane;
  5987. }());
  5988. BABYLON.Plane = Plane;
  5989. var Viewport = /** @class */ (function () {
  5990. /**
  5991. * Creates a Viewport object located at (x, y) and sized (width, height).
  5992. */
  5993. function Viewport(x, y, width, height) {
  5994. this.x = x;
  5995. this.y = y;
  5996. this.width = width;
  5997. this.height = height;
  5998. }
  5999. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6000. if (renderWidthOrEngine.getRenderWidth) {
  6001. var engine = renderWidthOrEngine;
  6002. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6003. }
  6004. var renderWidth = renderWidthOrEngine;
  6005. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6006. };
  6007. /**
  6008. * Returns a new Viewport copied from the current one.
  6009. */
  6010. Viewport.prototype.clone = function () {
  6011. return new Viewport(this.x, this.y, this.width, this.height);
  6012. };
  6013. return Viewport;
  6014. }());
  6015. BABYLON.Viewport = Viewport;
  6016. var Frustum = /** @class */ (function () {
  6017. function Frustum() {
  6018. }
  6019. /**
  6020. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6021. */
  6022. Frustum.GetPlanes = function (transform) {
  6023. var frustumPlanes = [];
  6024. for (var index = 0; index < 6; index++) {
  6025. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6026. }
  6027. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6028. return frustumPlanes;
  6029. };
  6030. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6031. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6032. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6033. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6034. frustumPlane.d = transform.m[15] + transform.m[14];
  6035. frustumPlane.normalize();
  6036. };
  6037. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6038. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6039. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6040. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6041. frustumPlane.d = transform.m[15] - transform.m[14];
  6042. frustumPlane.normalize();
  6043. };
  6044. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6045. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6046. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6047. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6048. frustumPlane.d = transform.m[15] + transform.m[12];
  6049. frustumPlane.normalize();
  6050. };
  6051. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6052. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6053. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6054. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6055. frustumPlane.d = transform.m[15] - transform.m[12];
  6056. frustumPlane.normalize();
  6057. };
  6058. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6059. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6060. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6061. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6062. frustumPlane.d = transform.m[15] - transform.m[13];
  6063. frustumPlane.normalize();
  6064. };
  6065. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6066. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6067. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6068. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6069. frustumPlane.d = transform.m[15] + transform.m[13];
  6070. frustumPlane.normalize();
  6071. };
  6072. /**
  6073. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6074. */
  6075. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6076. // Near
  6077. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6078. // Far
  6079. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6080. // Left
  6081. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6082. // Right
  6083. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6084. // Top
  6085. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6086. // Bottom
  6087. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6088. };
  6089. return Frustum;
  6090. }());
  6091. BABYLON.Frustum = Frustum;
  6092. var Space;
  6093. (function (Space) {
  6094. Space[Space["LOCAL"] = 0] = "LOCAL";
  6095. Space[Space["WORLD"] = 1] = "WORLD";
  6096. Space[Space["BONE"] = 2] = "BONE";
  6097. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6098. var Axis = /** @class */ (function () {
  6099. function Axis() {
  6100. }
  6101. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6102. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6103. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6104. return Axis;
  6105. }());
  6106. BABYLON.Axis = Axis;
  6107. ;
  6108. var BezierCurve = /** @class */ (function () {
  6109. function BezierCurve() {
  6110. }
  6111. /**
  6112. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6113. */
  6114. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6115. // Extract X (which is equal to time here)
  6116. var f0 = 1 - 3 * x2 + 3 * x1;
  6117. var f1 = 3 * x2 - 6 * x1;
  6118. var f2 = 3 * x1;
  6119. var refinedT = t;
  6120. for (var i = 0; i < 5; i++) {
  6121. var refinedT2 = refinedT * refinedT;
  6122. var refinedT3 = refinedT2 * refinedT;
  6123. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6124. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6125. refinedT -= (x - t) * slope;
  6126. refinedT = Math.min(1, Math.max(0, refinedT));
  6127. }
  6128. // Resolve cubic bezier for the given x
  6129. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6130. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6131. Math.pow(refinedT, 3);
  6132. };
  6133. return BezierCurve;
  6134. }());
  6135. BABYLON.BezierCurve = BezierCurve;
  6136. var Orientation;
  6137. (function (Orientation) {
  6138. Orientation[Orientation["CW"] = 0] = "CW";
  6139. Orientation[Orientation["CCW"] = 1] = "CCW";
  6140. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6141. var Angle = /** @class */ (function () {
  6142. /**
  6143. * Creates an Angle object of "radians" radians (float).
  6144. */
  6145. function Angle(radians) {
  6146. var _this = this;
  6147. /**
  6148. * Returns the Angle value in degrees (float).
  6149. */
  6150. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6151. /**
  6152. * Returns the Angle value in radians (float).
  6153. */
  6154. this.radians = function () { return _this._radians; };
  6155. this._radians = radians;
  6156. if (this._radians < 0.0)
  6157. this._radians += (2.0 * Math.PI);
  6158. }
  6159. /**
  6160. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6161. */
  6162. Angle.BetweenTwoPoints = function (a, b) {
  6163. var delta = b.subtract(a);
  6164. var theta = Math.atan2(delta.y, delta.x);
  6165. return new Angle(theta);
  6166. };
  6167. /**
  6168. * Returns a new Angle object from the passed float in radians.
  6169. */
  6170. Angle.FromRadians = function (radians) {
  6171. return new Angle(radians);
  6172. };
  6173. /**
  6174. * Returns a new Angle object from the passed float in degrees.
  6175. */
  6176. Angle.FromDegrees = function (degrees) {
  6177. return new Angle(degrees * Math.PI / 180.0);
  6178. };
  6179. return Angle;
  6180. }());
  6181. BABYLON.Angle = Angle;
  6182. var Arc2 = /** @class */ (function () {
  6183. /**
  6184. * Creates an Arc object from the three passed points : start, middle and end.
  6185. */
  6186. function Arc2(startPoint, midPoint, endPoint) {
  6187. this.startPoint = startPoint;
  6188. this.midPoint = midPoint;
  6189. this.endPoint = endPoint;
  6190. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6191. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6192. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6193. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6194. 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);
  6195. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6196. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6197. var a1 = this.startAngle.degrees();
  6198. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6199. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6200. // angles correction
  6201. if (a2 - a1 > +180.0)
  6202. a2 -= 360.0;
  6203. if (a2 - a1 < -180.0)
  6204. a2 += 360.0;
  6205. if (a3 - a2 > +180.0)
  6206. a3 -= 360.0;
  6207. if (a3 - a2 < -180.0)
  6208. a3 += 360.0;
  6209. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6210. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6211. }
  6212. return Arc2;
  6213. }());
  6214. BABYLON.Arc2 = Arc2;
  6215. var Path2 = /** @class */ (function () {
  6216. /**
  6217. * Creates a Path2 object from the starting 2D coordinates x and y.
  6218. */
  6219. function Path2(x, y) {
  6220. this._points = new Array();
  6221. this._length = 0.0;
  6222. this.closed = false;
  6223. this._points.push(new Vector2(x, y));
  6224. }
  6225. /**
  6226. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6227. * Returns the updated Path2.
  6228. */
  6229. Path2.prototype.addLineTo = function (x, y) {
  6230. if (this.closed) {
  6231. return this;
  6232. }
  6233. var newPoint = new Vector2(x, y);
  6234. var previousPoint = this._points[this._points.length - 1];
  6235. this._points.push(newPoint);
  6236. this._length += newPoint.subtract(previousPoint).length();
  6237. return this;
  6238. };
  6239. /**
  6240. * 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.
  6241. * Returns the updated Path2.
  6242. */
  6243. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6244. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6245. if (this.closed) {
  6246. return this;
  6247. }
  6248. var startPoint = this._points[this._points.length - 1];
  6249. var midPoint = new Vector2(midX, midY);
  6250. var endPoint = new Vector2(endX, endY);
  6251. var arc = new Arc2(startPoint, midPoint, endPoint);
  6252. var increment = arc.angle.radians() / numberOfSegments;
  6253. if (arc.orientation === Orientation.CW)
  6254. increment *= -1;
  6255. var currentAngle = arc.startAngle.radians() + increment;
  6256. for (var i = 0; i < numberOfSegments; i++) {
  6257. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6258. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6259. this.addLineTo(x, y);
  6260. currentAngle += increment;
  6261. }
  6262. return this;
  6263. };
  6264. /**
  6265. * Closes the Path2.
  6266. * Returns the Path2.
  6267. */
  6268. Path2.prototype.close = function () {
  6269. this.closed = true;
  6270. return this;
  6271. };
  6272. /**
  6273. * Returns the Path2 total length (float).
  6274. */
  6275. Path2.prototype.length = function () {
  6276. var result = this._length;
  6277. if (!this.closed) {
  6278. var lastPoint = this._points[this._points.length - 1];
  6279. var firstPoint = this._points[0];
  6280. result += (firstPoint.subtract(lastPoint).length());
  6281. }
  6282. return result;
  6283. };
  6284. /**
  6285. * Returns the Path2 internal array of points.
  6286. */
  6287. Path2.prototype.getPoints = function () {
  6288. return this._points;
  6289. };
  6290. /**
  6291. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6292. */
  6293. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6294. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6295. return Vector2.Zero();
  6296. }
  6297. var lengthPosition = normalizedLengthPosition * this.length();
  6298. var previousOffset = 0;
  6299. for (var i = 0; i < this._points.length; i++) {
  6300. var j = (i + 1) % this._points.length;
  6301. var a = this._points[i];
  6302. var b = this._points[j];
  6303. var bToA = b.subtract(a);
  6304. var nextOffset = (bToA.length() + previousOffset);
  6305. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6306. var dir = bToA.normalize();
  6307. var localOffset = lengthPosition - previousOffset;
  6308. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6309. }
  6310. previousOffset = nextOffset;
  6311. }
  6312. return Vector2.Zero();
  6313. };
  6314. /**
  6315. * Returns a new Path2 starting at the coordinates (x, y).
  6316. */
  6317. Path2.StartingAt = function (x, y) {
  6318. return new Path2(x, y);
  6319. };
  6320. return Path2;
  6321. }());
  6322. BABYLON.Path2 = Path2;
  6323. var Path3D = /** @class */ (function () {
  6324. /**
  6325. * new Path3D(path, normal, raw)
  6326. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6327. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6328. * path : an array of Vector3, the curve axis of the Path3D
  6329. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6330. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6331. */
  6332. function Path3D(path, firstNormal, raw) {
  6333. if (firstNormal === void 0) { firstNormal = null; }
  6334. this.path = path;
  6335. this._curve = new Array();
  6336. this._distances = new Array();
  6337. this._tangents = new Array();
  6338. this._normals = new Array();
  6339. this._binormals = new Array();
  6340. for (var p = 0; p < path.length; p++) {
  6341. this._curve[p] = path[p].clone(); // hard copy
  6342. }
  6343. this._raw = raw || false;
  6344. this._compute(firstNormal);
  6345. }
  6346. /**
  6347. * Returns the Path3D array of successive Vector3 designing its curve.
  6348. */
  6349. Path3D.prototype.getCurve = function () {
  6350. return this._curve;
  6351. };
  6352. /**
  6353. * Returns an array populated with tangent vectors on each Path3D curve point.
  6354. */
  6355. Path3D.prototype.getTangents = function () {
  6356. return this._tangents;
  6357. };
  6358. /**
  6359. * Returns an array populated with normal vectors on each Path3D curve point.
  6360. */
  6361. Path3D.prototype.getNormals = function () {
  6362. return this._normals;
  6363. };
  6364. /**
  6365. * Returns an array populated with binormal vectors on each Path3D curve point.
  6366. */
  6367. Path3D.prototype.getBinormals = function () {
  6368. return this._binormals;
  6369. };
  6370. /**
  6371. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6372. */
  6373. Path3D.prototype.getDistances = function () {
  6374. return this._distances;
  6375. };
  6376. /**
  6377. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6378. * Returns the same object updated.
  6379. */
  6380. Path3D.prototype.update = function (path, firstNormal) {
  6381. if (firstNormal === void 0) { firstNormal = null; }
  6382. for (var p = 0; p < path.length; p++) {
  6383. this._curve[p].x = path[p].x;
  6384. this._curve[p].y = path[p].y;
  6385. this._curve[p].z = path[p].z;
  6386. }
  6387. this._compute(firstNormal);
  6388. return this;
  6389. };
  6390. // private function compute() : computes tangents, normals and binormals
  6391. Path3D.prototype._compute = function (firstNormal) {
  6392. var l = this._curve.length;
  6393. // first and last tangents
  6394. this._tangents[0] = this._getFirstNonNullVector(0);
  6395. if (!this._raw) {
  6396. this._tangents[0].normalize();
  6397. }
  6398. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6399. if (!this._raw) {
  6400. this._tangents[l - 1].normalize();
  6401. }
  6402. // normals and binormals at first point : arbitrary vector with _normalVector()
  6403. var tg0 = this._tangents[0];
  6404. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6405. this._normals[0] = pp0;
  6406. if (!this._raw) {
  6407. this._normals[0].normalize();
  6408. }
  6409. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6410. if (!this._raw) {
  6411. this._binormals[0].normalize();
  6412. }
  6413. this._distances[0] = 0.0;
  6414. // normals and binormals : next points
  6415. var prev; // previous vector (segment)
  6416. var cur; // current vector (segment)
  6417. var curTang; // current tangent
  6418. // previous normal
  6419. var prevBinor; // previous binormal
  6420. for (var i = 1; i < l; i++) {
  6421. // tangents
  6422. prev = this._getLastNonNullVector(i);
  6423. if (i < l - 1) {
  6424. cur = this._getFirstNonNullVector(i);
  6425. this._tangents[i] = prev.add(cur);
  6426. this._tangents[i].normalize();
  6427. }
  6428. this._distances[i] = this._distances[i - 1] + prev.length();
  6429. // normals and binormals
  6430. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6431. curTang = this._tangents[i];
  6432. prevBinor = this._binormals[i - 1];
  6433. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6434. if (!this._raw) {
  6435. this._normals[i].normalize();
  6436. }
  6437. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6438. if (!this._raw) {
  6439. this._binormals[i].normalize();
  6440. }
  6441. }
  6442. };
  6443. // private function getFirstNonNullVector(index)
  6444. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6445. Path3D.prototype._getFirstNonNullVector = function (index) {
  6446. var i = 1;
  6447. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6448. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6449. i++;
  6450. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6451. }
  6452. return nNVector;
  6453. };
  6454. // private function getLastNonNullVector(index)
  6455. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6456. Path3D.prototype._getLastNonNullVector = function (index) {
  6457. var i = 1;
  6458. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6459. while (nLVector.length() === 0 && index > i + 1) {
  6460. i++;
  6461. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6462. }
  6463. return nLVector;
  6464. };
  6465. // private function normalVector(v0, vt, va) :
  6466. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6467. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6468. Path3D.prototype._normalVector = function (v0, vt, va) {
  6469. var normal0;
  6470. var tgl = vt.length();
  6471. if (tgl === 0.0) {
  6472. tgl = 1.0;
  6473. }
  6474. if (va === undefined || va === null) {
  6475. var point;
  6476. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6477. point = new Vector3(0.0, -1.0, 0.0);
  6478. }
  6479. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6480. point = new Vector3(1.0, 0.0, 0.0);
  6481. }
  6482. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6483. point = new Vector3(0.0, 0.0, 1.0);
  6484. }
  6485. else {
  6486. point = Vector3.Zero();
  6487. }
  6488. normal0 = Vector3.Cross(vt, point);
  6489. }
  6490. else {
  6491. normal0 = Vector3.Cross(vt, va);
  6492. Vector3.CrossToRef(normal0, vt, normal0);
  6493. }
  6494. normal0.normalize();
  6495. return normal0;
  6496. };
  6497. return Path3D;
  6498. }());
  6499. BABYLON.Path3D = Path3D;
  6500. var Curve3 = /** @class */ (function () {
  6501. /**
  6502. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6503. * A Curve3 is designed from a series of successive Vector3.
  6504. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6505. */
  6506. function Curve3(points) {
  6507. this._length = 0.0;
  6508. this._points = points;
  6509. this._length = this._computeLength(points);
  6510. }
  6511. /**
  6512. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6513. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6514. * @param v1 (Vector3) the control point
  6515. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6516. * @param nbPoints (integer) the wanted number of points in the curve
  6517. */
  6518. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6519. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6520. var bez = new Array();
  6521. var equation = function (t, val0, val1, val2) {
  6522. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6523. return res;
  6524. };
  6525. for (var i = 0; i <= nbPoints; i++) {
  6526. 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)));
  6527. }
  6528. return new Curve3(bez);
  6529. };
  6530. /**
  6531. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6532. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6533. * @param v1 (Vector3) the first control point
  6534. * @param v2 (Vector3) the second control point
  6535. * @param v3 (Vector3) the end point of the Cubic Bezier
  6536. * @param nbPoints (integer) the wanted number of points in the curve
  6537. */
  6538. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6539. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6540. var bez = new Array();
  6541. var equation = function (t, val0, val1, val2, val3) {
  6542. 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;
  6543. return res;
  6544. };
  6545. for (var i = 0; i <= nbPoints; i++) {
  6546. 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)));
  6547. }
  6548. return new Curve3(bez);
  6549. };
  6550. /**
  6551. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6552. * @param p1 (Vector3) the origin point of the Hermite Spline
  6553. * @param t1 (Vector3) the tangent vector at the origin point
  6554. * @param p2 (Vector3) the end point of the Hermite Spline
  6555. * @param t2 (Vector3) the tangent vector at the end point
  6556. * @param nbPoints (integer) the wanted number of points in the curve
  6557. */
  6558. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6559. var hermite = new Array();
  6560. var step = 1.0 / nbPoints;
  6561. for (var i = 0; i <= nbPoints; i++) {
  6562. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6563. }
  6564. return new Curve3(hermite);
  6565. };
  6566. /**
  6567. * Returns a Curve3 object along a CatmullRom Spline curve :
  6568. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6569. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6570. */
  6571. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6572. var totalPoints = new Array();
  6573. totalPoints.push(points[0].clone());
  6574. Array.prototype.push.apply(totalPoints, points);
  6575. totalPoints.push(points[points.length - 1].clone());
  6576. var catmullRom = new Array();
  6577. var step = 1.0 / nbPoints;
  6578. var amount = 0.0;
  6579. for (var i = 0; i < totalPoints.length - 3; i++) {
  6580. amount = 0;
  6581. for (var c = 0; c < nbPoints; c++) {
  6582. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6583. amount += step;
  6584. }
  6585. }
  6586. i--;
  6587. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6588. return new Curve3(catmullRom);
  6589. };
  6590. /**
  6591. * Returns the Curve3 stored array of successive Vector3
  6592. */
  6593. Curve3.prototype.getPoints = function () {
  6594. return this._points;
  6595. };
  6596. /**
  6597. * Returns the computed length (float) of the curve.
  6598. */
  6599. Curve3.prototype.length = function () {
  6600. return this._length;
  6601. };
  6602. /**
  6603. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6604. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6605. * curveA and curveB keep unchanged.
  6606. */
  6607. Curve3.prototype.continue = function (curve) {
  6608. var lastPoint = this._points[this._points.length - 1];
  6609. var continuedPoints = this._points.slice();
  6610. var curvePoints = curve.getPoints();
  6611. for (var i = 1; i < curvePoints.length; i++) {
  6612. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6613. }
  6614. var continuedCurve = new Curve3(continuedPoints);
  6615. return continuedCurve;
  6616. };
  6617. Curve3.prototype._computeLength = function (path) {
  6618. var l = 0;
  6619. for (var i = 1; i < path.length; i++) {
  6620. l += (path[i].subtract(path[i - 1])).length();
  6621. }
  6622. return l;
  6623. };
  6624. return Curve3;
  6625. }());
  6626. BABYLON.Curve3 = Curve3;
  6627. // Vertex formats
  6628. var PositionNormalVertex = /** @class */ (function () {
  6629. function PositionNormalVertex(position, normal) {
  6630. if (position === void 0) { position = Vector3.Zero(); }
  6631. if (normal === void 0) { normal = Vector3.Up(); }
  6632. this.position = position;
  6633. this.normal = normal;
  6634. }
  6635. PositionNormalVertex.prototype.clone = function () {
  6636. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6637. };
  6638. return PositionNormalVertex;
  6639. }());
  6640. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6641. var PositionNormalTextureVertex = /** @class */ (function () {
  6642. function PositionNormalTextureVertex(position, normal, uv) {
  6643. if (position === void 0) { position = Vector3.Zero(); }
  6644. if (normal === void 0) { normal = Vector3.Up(); }
  6645. if (uv === void 0) { uv = Vector2.Zero(); }
  6646. this.position = position;
  6647. this.normal = normal;
  6648. this.uv = uv;
  6649. }
  6650. PositionNormalTextureVertex.prototype.clone = function () {
  6651. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6652. };
  6653. return PositionNormalTextureVertex;
  6654. }());
  6655. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6656. // Temporary pre-allocated objects for engine internal use
  6657. // usage in any internal function :
  6658. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6659. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6660. var Tmp = /** @class */ (function () {
  6661. function Tmp() {
  6662. }
  6663. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6664. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6665. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6666. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6667. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6668. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6669. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6670. Matrix.Zero(), Matrix.Zero(),
  6671. Matrix.Zero(), Matrix.Zero(),
  6672. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6673. return Tmp;
  6674. }());
  6675. BABYLON.Tmp = Tmp;
  6676. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6677. var MathTmp = /** @class */ (function () {
  6678. function MathTmp() {
  6679. }
  6680. MathTmp.Vector3 = [Vector3.Zero()];
  6681. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6682. MathTmp.Quaternion = [Quaternion.Zero()];
  6683. return MathTmp;
  6684. }());
  6685. })(BABYLON || (BABYLON = {}));
  6686. //# sourceMappingURL=babylon.math.js.map
  6687. var BABYLON;
  6688. (function (BABYLON) {
  6689. var Scalar = /** @class */ (function () {
  6690. function Scalar() {
  6691. }
  6692. /**
  6693. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6694. */
  6695. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6696. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6697. var num = a - b;
  6698. return -epsilon <= num && num <= epsilon;
  6699. };
  6700. /**
  6701. * Returns a string : the upper case translation of the number i to hexadecimal.
  6702. */
  6703. Scalar.ToHex = function (i) {
  6704. var str = i.toString(16);
  6705. if (i <= 15) {
  6706. return ("0" + str).toUpperCase();
  6707. }
  6708. return str.toUpperCase();
  6709. };
  6710. /**
  6711. * Returns -1 if value is negative and +1 is value is positive.
  6712. * Returns the value itself if it's equal to zero.
  6713. */
  6714. Scalar.Sign = function (value) {
  6715. value = +value; // convert to a number
  6716. if (value === 0 || isNaN(value))
  6717. return value;
  6718. return value > 0 ? 1 : -1;
  6719. };
  6720. /**
  6721. * Returns the value itself if it's between min and max.
  6722. * Returns min if the value is lower than min.
  6723. * Returns max if the value is greater than max.
  6724. */
  6725. Scalar.Clamp = function (value, min, max) {
  6726. if (min === void 0) { min = 0; }
  6727. if (max === void 0) { max = 1; }
  6728. return Math.min(max, Math.max(min, value));
  6729. };
  6730. /**
  6731. * Returns the log2 of value.
  6732. */
  6733. Scalar.Log2 = function (value) {
  6734. return Math.log(value) * Math.LOG2E;
  6735. };
  6736. /**
  6737. * Loops the value, so that it is never larger than length and never smaller than 0.
  6738. *
  6739. * This is similar to the modulo operator but it works with floating point numbers.
  6740. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6741. * With t = 5 and length = 2.5, the result would be 0.0.
  6742. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6743. */
  6744. Scalar.Repeat = function (value, length) {
  6745. return value - Math.floor(value / length) * length;
  6746. };
  6747. /**
  6748. * Normalize the value between 0.0 and 1.0 using min and max values
  6749. */
  6750. Scalar.Normalize = function (value, min, max) {
  6751. return (value - min) / (max - min);
  6752. };
  6753. /**
  6754. * Denormalize the value from 0.0 and 1.0 using min and max values
  6755. */
  6756. Scalar.Denormalize = function (normalized, min, max) {
  6757. return (normalized * (max - min) + min);
  6758. };
  6759. /**
  6760. * Calculates the shortest difference between two given angles given in degrees.
  6761. */
  6762. Scalar.DeltaAngle = function (current, target) {
  6763. var num = Scalar.Repeat(target - current, 360.0);
  6764. if (num > 180.0) {
  6765. num -= 360.0;
  6766. }
  6767. return num;
  6768. };
  6769. /**
  6770. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6771. *
  6772. * The returned value will move back and forth between 0 and length
  6773. */
  6774. Scalar.PingPong = function (tx, length) {
  6775. var t = Scalar.Repeat(tx, length * 2.0);
  6776. return length - Math.abs(t - length);
  6777. };
  6778. /**
  6779. * Interpolates between min and max with smoothing at the limits.
  6780. *
  6781. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6782. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6783. */
  6784. Scalar.SmoothStep = function (from, to, tx) {
  6785. var t = Scalar.Clamp(tx);
  6786. t = -2.0 * t * t * t + 3.0 * t * t;
  6787. return to * t + from * (1.0 - t);
  6788. };
  6789. /**
  6790. * Moves a value current towards target.
  6791. *
  6792. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6793. * Negative values of maxDelta pushes the value away from target.
  6794. */
  6795. Scalar.MoveTowards = function (current, target, maxDelta) {
  6796. var result = 0;
  6797. if (Math.abs(target - current) <= maxDelta) {
  6798. result = target;
  6799. }
  6800. else {
  6801. result = current + Scalar.Sign(target - current) * maxDelta;
  6802. }
  6803. return result;
  6804. };
  6805. /**
  6806. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6807. *
  6808. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6809. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6810. */
  6811. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6812. var num = Scalar.DeltaAngle(current, target);
  6813. var result = 0;
  6814. if (-maxDelta < num && num < maxDelta) {
  6815. result = target;
  6816. }
  6817. else {
  6818. target = current + num;
  6819. result = Scalar.MoveTowards(current, target, maxDelta);
  6820. }
  6821. return result;
  6822. };
  6823. /**
  6824. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6825. */
  6826. Scalar.Lerp = function (start, end, amount) {
  6827. return start + ((end - start) * amount);
  6828. };
  6829. /**
  6830. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6831. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6832. */
  6833. Scalar.LerpAngle = function (start, end, amount) {
  6834. var num = Scalar.Repeat(end - start, 360.0);
  6835. if (num > 180.0) {
  6836. num -= 360.0;
  6837. }
  6838. return start + num * Scalar.Clamp(amount);
  6839. };
  6840. /**
  6841. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6842. */
  6843. Scalar.InverseLerp = function (a, b, value) {
  6844. var result = 0;
  6845. if (a != b) {
  6846. result = Scalar.Clamp((value - a) / (b - a));
  6847. }
  6848. else {
  6849. result = 0.0;
  6850. }
  6851. return result;
  6852. };
  6853. /**
  6854. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6855. */
  6856. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6857. var squared = amount * amount;
  6858. var cubed = amount * squared;
  6859. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6860. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6861. var part3 = (cubed - (2.0 * squared)) + amount;
  6862. var part4 = cubed - squared;
  6863. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6864. };
  6865. /**
  6866. * Returns a random float number between and min and max values
  6867. */
  6868. Scalar.RandomRange = function (min, max) {
  6869. if (min === max)
  6870. return min;
  6871. return ((Math.random() * (max - min)) + min);
  6872. };
  6873. /**
  6874. * This function returns percentage of a number in a given range.
  6875. *
  6876. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6877. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6878. */
  6879. Scalar.RangeToPercent = function (number, min, max) {
  6880. return ((number - min) / (max - min));
  6881. };
  6882. /**
  6883. * This function returns number that corresponds to the percentage in a given range.
  6884. *
  6885. * PercentToRange(0.34,0,100) will return 34.
  6886. */
  6887. Scalar.PercentToRange = function (percent, min, max) {
  6888. return ((max - min) * percent + min);
  6889. };
  6890. /**
  6891. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6892. * @param angle The angle to normalize in radian.
  6893. * @return The converted angle.
  6894. */
  6895. Scalar.NormalizeRadians = function (angle) {
  6896. // More precise but slower version kept for reference.
  6897. // angle = angle % Tools.TwoPi;
  6898. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6899. //if (angle > Math.PI) {
  6900. // angle -= Tools.TwoPi;
  6901. //}
  6902. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6903. return angle;
  6904. };
  6905. /**
  6906. * Two pi constants convenient for computation.
  6907. */
  6908. Scalar.TwoPi = Math.PI * 2;
  6909. return Scalar;
  6910. }());
  6911. BABYLON.Scalar = Scalar;
  6912. })(BABYLON || (BABYLON = {}));
  6913. //# sourceMappingURL=babylon.math.scalar.js.map
  6914. //# sourceMappingURL=babylon.mixins.js.map
  6915. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6916. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6917. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6918. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6919. //# sourceMappingURL=babylon.webgl2.js.map
  6920. var BABYLON;
  6921. (function (BABYLON) {
  6922. var __decoratorInitialStore = {};
  6923. var __mergedStore = {};
  6924. var _copySource = function (creationFunction, source, instanciate) {
  6925. var destination = creationFunction();
  6926. // Tags
  6927. if (BABYLON.Tags) {
  6928. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6929. }
  6930. var classStore = getMergedStore(destination);
  6931. // Properties
  6932. for (var property in classStore) {
  6933. var propertyDescriptor = classStore[property];
  6934. var sourceProperty = source[property];
  6935. var propertyType = propertyDescriptor.type;
  6936. if (sourceProperty !== undefined && sourceProperty !== null) {
  6937. switch (propertyType) {
  6938. case 0: // Value
  6939. case 6:// Mesh reference
  6940. destination[property] = sourceProperty;
  6941. break;
  6942. case 1:// Texture
  6943. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6944. break;
  6945. case 2: // Color3
  6946. case 3: // FresnelParameters
  6947. case 4: // Vector2
  6948. case 5: // Vector3
  6949. case 7: // Color Curves
  6950. case 10:// Quaternion
  6951. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6952. break;
  6953. }
  6954. }
  6955. }
  6956. return destination;
  6957. };
  6958. function getDirectStore(target) {
  6959. var classKey = target.getClassName();
  6960. if (!__decoratorInitialStore[classKey]) {
  6961. __decoratorInitialStore[classKey] = {};
  6962. }
  6963. return __decoratorInitialStore[classKey];
  6964. }
  6965. /**
  6966. * Return the list of properties flagged as serializable
  6967. * @param target: host object
  6968. */
  6969. function getMergedStore(target) {
  6970. var classKey = target.getClassName();
  6971. if (__mergedStore[classKey]) {
  6972. return __mergedStore[classKey];
  6973. }
  6974. __mergedStore[classKey] = {};
  6975. var store = __mergedStore[classKey];
  6976. var currentTarget = target;
  6977. var currentKey = classKey;
  6978. while (currentKey) {
  6979. var initialStore = __decoratorInitialStore[currentKey];
  6980. for (var property in initialStore) {
  6981. store[property] = initialStore[property];
  6982. }
  6983. var parent_1 = void 0;
  6984. var done = false;
  6985. do {
  6986. parent_1 = Object.getPrototypeOf(currentTarget);
  6987. if (!parent_1.getClassName) {
  6988. done = true;
  6989. break;
  6990. }
  6991. if (parent_1.getClassName() !== currentKey) {
  6992. break;
  6993. }
  6994. currentTarget = parent_1;
  6995. } while (parent_1);
  6996. if (done) {
  6997. break;
  6998. }
  6999. currentKey = parent_1.getClassName();
  7000. currentTarget = parent_1;
  7001. }
  7002. return store;
  7003. }
  7004. function generateSerializableMember(type, sourceName) {
  7005. return function (target, propertyKey) {
  7006. var classStore = getDirectStore(target);
  7007. if (!classStore[propertyKey]) {
  7008. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7009. }
  7010. };
  7011. }
  7012. function generateExpandMember(setCallback, targetKey) {
  7013. if (targetKey === void 0) { targetKey = null; }
  7014. return function (target, propertyKey) {
  7015. var key = targetKey || ("_" + propertyKey);
  7016. Object.defineProperty(target, propertyKey, {
  7017. get: function () {
  7018. return this[key];
  7019. },
  7020. set: function (value) {
  7021. if (this[key] === value) {
  7022. return;
  7023. }
  7024. this[key] = value;
  7025. target[setCallback].apply(this);
  7026. },
  7027. enumerable: true,
  7028. configurable: true
  7029. });
  7030. };
  7031. }
  7032. function expandToProperty(callback, targetKey) {
  7033. if (targetKey === void 0) { targetKey = null; }
  7034. return generateExpandMember(callback, targetKey);
  7035. }
  7036. BABYLON.expandToProperty = expandToProperty;
  7037. function serialize(sourceName) {
  7038. return generateSerializableMember(0, sourceName); // value member
  7039. }
  7040. BABYLON.serialize = serialize;
  7041. function serializeAsTexture(sourceName) {
  7042. return generateSerializableMember(1, sourceName); // texture member
  7043. }
  7044. BABYLON.serializeAsTexture = serializeAsTexture;
  7045. function serializeAsColor3(sourceName) {
  7046. return generateSerializableMember(2, sourceName); // color3 member
  7047. }
  7048. BABYLON.serializeAsColor3 = serializeAsColor3;
  7049. function serializeAsFresnelParameters(sourceName) {
  7050. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7051. }
  7052. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7053. function serializeAsVector2(sourceName) {
  7054. return generateSerializableMember(4, sourceName); // vector2 member
  7055. }
  7056. BABYLON.serializeAsVector2 = serializeAsVector2;
  7057. function serializeAsVector3(sourceName) {
  7058. return generateSerializableMember(5, sourceName); // vector3 member
  7059. }
  7060. BABYLON.serializeAsVector3 = serializeAsVector3;
  7061. function serializeAsMeshReference(sourceName) {
  7062. return generateSerializableMember(6, sourceName); // mesh reference member
  7063. }
  7064. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7065. function serializeAsColorCurves(sourceName) {
  7066. return generateSerializableMember(7, sourceName); // color curves
  7067. }
  7068. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7069. function serializeAsColor4(sourceName) {
  7070. return generateSerializableMember(8, sourceName); // color 4
  7071. }
  7072. BABYLON.serializeAsColor4 = serializeAsColor4;
  7073. function serializeAsImageProcessingConfiguration(sourceName) {
  7074. return generateSerializableMember(9, sourceName); // image processing
  7075. }
  7076. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7077. function serializeAsQuaternion(sourceName) {
  7078. return generateSerializableMember(10, sourceName); // quaternion member
  7079. }
  7080. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7081. var SerializationHelper = /** @class */ (function () {
  7082. function SerializationHelper() {
  7083. }
  7084. SerializationHelper.Serialize = function (entity, serializationObject) {
  7085. if (!serializationObject) {
  7086. serializationObject = {};
  7087. }
  7088. // Tags
  7089. if (BABYLON.Tags) {
  7090. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7091. }
  7092. var serializedProperties = getMergedStore(entity);
  7093. // Properties
  7094. for (var property in serializedProperties) {
  7095. var propertyDescriptor = serializedProperties[property];
  7096. var targetPropertyName = propertyDescriptor.sourceName || property;
  7097. var propertyType = propertyDescriptor.type;
  7098. var sourceProperty = entity[property];
  7099. if (sourceProperty !== undefined && sourceProperty !== null) {
  7100. switch (propertyType) {
  7101. case 0:// Value
  7102. serializationObject[targetPropertyName] = sourceProperty;
  7103. break;
  7104. case 1:// Texture
  7105. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7106. break;
  7107. case 2:// Color3
  7108. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7109. break;
  7110. case 3:// FresnelParameters
  7111. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7112. break;
  7113. case 4:// Vector2
  7114. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7115. break;
  7116. case 5:// Vector3
  7117. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7118. break;
  7119. case 6:// Mesh reference
  7120. serializationObject[targetPropertyName] = sourceProperty.id;
  7121. break;
  7122. case 7:// Color Curves
  7123. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7124. break;
  7125. case 8:// Color 4
  7126. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7127. break;
  7128. case 9:// Image Processing
  7129. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7130. break;
  7131. }
  7132. }
  7133. }
  7134. return serializationObject;
  7135. };
  7136. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7137. if (rootUrl === void 0) { rootUrl = null; }
  7138. var destination = creationFunction();
  7139. if (!rootUrl) {
  7140. rootUrl = "";
  7141. }
  7142. // Tags
  7143. if (BABYLON.Tags) {
  7144. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7145. }
  7146. var classStore = getMergedStore(destination);
  7147. // Properties
  7148. for (var property in classStore) {
  7149. var propertyDescriptor = classStore[property];
  7150. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7151. var propertyType = propertyDescriptor.type;
  7152. if (sourceProperty !== undefined && sourceProperty !== null) {
  7153. var dest = destination;
  7154. switch (propertyType) {
  7155. case 0:// Value
  7156. dest[property] = sourceProperty;
  7157. break;
  7158. case 1:// Texture
  7159. if (scene) {
  7160. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7161. }
  7162. break;
  7163. case 2:// Color3
  7164. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7165. break;
  7166. case 3:// FresnelParameters
  7167. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7168. break;
  7169. case 4:// Vector2
  7170. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7171. break;
  7172. case 5:// Vector3
  7173. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7174. break;
  7175. case 6:// Mesh reference
  7176. if (scene) {
  7177. dest[property] = scene.getLastMeshByID(sourceProperty);
  7178. }
  7179. break;
  7180. case 7:// Color Curves
  7181. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7182. break;
  7183. case 8:// Color 4
  7184. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7185. break;
  7186. case 9:// Image Processing
  7187. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7188. break;
  7189. }
  7190. }
  7191. }
  7192. return destination;
  7193. };
  7194. SerializationHelper.Clone = function (creationFunction, source) {
  7195. return _copySource(creationFunction, source, false);
  7196. };
  7197. SerializationHelper.Instanciate = function (creationFunction, source) {
  7198. return _copySource(creationFunction, source, true);
  7199. };
  7200. return SerializationHelper;
  7201. }());
  7202. BABYLON.SerializationHelper = SerializationHelper;
  7203. })(BABYLON || (BABYLON = {}));
  7204. //# sourceMappingURL=babylon.decorators.js.map
  7205. var BABYLON;
  7206. (function (BABYLON) {
  7207. /**
  7208. * Wrapper class for promise with external resolve and reject.
  7209. */
  7210. var Deferred = /** @class */ (function () {
  7211. /**
  7212. * Constructor for this deferred object.
  7213. */
  7214. function Deferred() {
  7215. var _this = this;
  7216. this.promise = new Promise(function (resolve, reject) {
  7217. _this._resolve = resolve;
  7218. _this._reject = reject;
  7219. });
  7220. }
  7221. Object.defineProperty(Deferred.prototype, "resolve", {
  7222. /**
  7223. * The resolve method of the promise associated with this deferred object.
  7224. */
  7225. get: function () {
  7226. return this._resolve;
  7227. },
  7228. enumerable: true,
  7229. configurable: true
  7230. });
  7231. Object.defineProperty(Deferred.prototype, "reject", {
  7232. /**
  7233. * The reject method of the promise associated with this deferred object.
  7234. */
  7235. get: function () {
  7236. return this._reject;
  7237. },
  7238. enumerable: true,
  7239. configurable: true
  7240. });
  7241. return Deferred;
  7242. }());
  7243. BABYLON.Deferred = Deferred;
  7244. })(BABYLON || (BABYLON = {}));
  7245. //# sourceMappingURL=babylon.deferred.js.map
  7246. var BABYLON;
  7247. (function (BABYLON) {
  7248. /**
  7249. * A class serves as a medium between the observable and its observers
  7250. */
  7251. var EventState = /** @class */ (function () {
  7252. /**
  7253. * Create a new EventState
  7254. * @param mask defines the mask associated with this state
  7255. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7256. * @param target defines the original target of the state
  7257. * @param currentTarget defines the current target of the state
  7258. */
  7259. function EventState(mask, skipNextObservers, target, currentTarget) {
  7260. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7261. this.initalize(mask, skipNextObservers, target, currentTarget);
  7262. }
  7263. /**
  7264. * Initialize the current event state
  7265. * @param mask defines the mask associated with this state
  7266. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7267. * @param target defines the original target of the state
  7268. * @param currentTarget defines the current target of the state
  7269. * @returns the current event state
  7270. */
  7271. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7272. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7273. this.mask = mask;
  7274. this.skipNextObservers = skipNextObservers;
  7275. this.target = target;
  7276. this.currentTarget = currentTarget;
  7277. return this;
  7278. };
  7279. return EventState;
  7280. }());
  7281. BABYLON.EventState = EventState;
  7282. /**
  7283. * Represent an Observer registered to a given Observable object.
  7284. */
  7285. var Observer = /** @class */ (function () {
  7286. /**
  7287. * Creates a new observer
  7288. * @param callback defines the callback to call when the observer is notified
  7289. * @param mask defines the mask of the observer (used to filter notifications)
  7290. * @param scope defines the current scope used to restore the JS context
  7291. */
  7292. function Observer(
  7293. /**
  7294. * Defines the callback to call when the observer is notified
  7295. */
  7296. callback,
  7297. /**
  7298. * Defines the mask of the observer (used to filter notifications)
  7299. */
  7300. mask,
  7301. /**
  7302. * Defines the current scope used to restore the JS context
  7303. */
  7304. scope) {
  7305. if (scope === void 0) { scope = null; }
  7306. this.callback = callback;
  7307. this.mask = mask;
  7308. this.scope = scope;
  7309. /** @ignore */
  7310. this._willBeUnregistered = false;
  7311. /**
  7312. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7313. */
  7314. this.unregisterOnNextCall = false;
  7315. }
  7316. return Observer;
  7317. }());
  7318. BABYLON.Observer = Observer;
  7319. /**
  7320. * Represent a list of observers registered to multiple Observables object.
  7321. */
  7322. var MultiObserver = /** @class */ (function () {
  7323. function MultiObserver() {
  7324. }
  7325. /**
  7326. * Release associated resources
  7327. */
  7328. MultiObserver.prototype.dispose = function () {
  7329. if (this._observers && this._observables) {
  7330. for (var index = 0; index < this._observers.length; index++) {
  7331. this._observables[index].remove(this._observers[index]);
  7332. }
  7333. }
  7334. this._observers = null;
  7335. this._observables = null;
  7336. };
  7337. /**
  7338. * Raise a callback when one of the observable will notify
  7339. * @param observables defines a list of observables to watch
  7340. * @param callback defines the callback to call on notification
  7341. * @param mask defines the mask used to filter notifications
  7342. * @param scope defines the current scope used to restore the JS context
  7343. * @returns the new MultiObserver
  7344. */
  7345. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7346. if (mask === void 0) { mask = -1; }
  7347. if (scope === void 0) { scope = null; }
  7348. var result = new MultiObserver();
  7349. result._observers = new Array();
  7350. result._observables = observables;
  7351. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7352. var observable = observables_1[_i];
  7353. var observer = observable.add(callback, mask, false, scope);
  7354. if (observer) {
  7355. result._observers.push(observer);
  7356. }
  7357. }
  7358. return result;
  7359. };
  7360. return MultiObserver;
  7361. }());
  7362. BABYLON.MultiObserver = MultiObserver;
  7363. /**
  7364. * The Observable class is a simple implementation of the Observable pattern.
  7365. * 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.
  7366. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7367. * 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).
  7368. * 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.
  7369. */
  7370. var Observable = /** @class */ (function () {
  7371. /**
  7372. * Creates a new observable
  7373. * @param onObserverAdded defines a callback to call when a new observer is added
  7374. */
  7375. function Observable(onObserverAdded) {
  7376. this._observers = new Array();
  7377. this._eventState = new EventState(0);
  7378. if (onObserverAdded) {
  7379. this._onObserverAdded = onObserverAdded;
  7380. }
  7381. }
  7382. /**
  7383. * Create a new Observer with the specified callback
  7384. * @param callback the callback that will be executed for that Observer
  7385. * @param mask the mask used to filter observers
  7386. * @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.
  7387. * @param scope optional scope for the callback to be called from
  7388. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7389. * @returns the new observer created for the callback
  7390. */
  7391. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7392. if (mask === void 0) { mask = -1; }
  7393. if (insertFirst === void 0) { insertFirst = false; }
  7394. if (scope === void 0) { scope = null; }
  7395. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7396. if (!callback) {
  7397. return null;
  7398. }
  7399. var observer = new Observer(callback, mask, scope);
  7400. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7401. if (insertFirst) {
  7402. this._observers.unshift(observer);
  7403. }
  7404. else {
  7405. this._observers.push(observer);
  7406. }
  7407. if (this._onObserverAdded) {
  7408. this._onObserverAdded(observer);
  7409. }
  7410. return observer;
  7411. };
  7412. /**
  7413. * Remove an Observer from the Observable object
  7414. * @param observer the instance of the Observer to remove
  7415. * @returns false if it doesn't belong to this Observable
  7416. */
  7417. Observable.prototype.remove = function (observer) {
  7418. if (!observer) {
  7419. return false;
  7420. }
  7421. var index = this._observers.indexOf(observer);
  7422. if (index !== -1) {
  7423. this._observers.splice(index, 1);
  7424. return true;
  7425. }
  7426. return false;
  7427. };
  7428. /**
  7429. * Remove a callback from the Observable object
  7430. * @param callback the callback to remove
  7431. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7432. * @returns false if it doesn't belong to this Observable
  7433. */
  7434. Observable.prototype.removeCallback = function (callback, scope) {
  7435. for (var index = 0; index < this._observers.length; index++) {
  7436. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7437. this._observers.splice(index, 1);
  7438. return true;
  7439. }
  7440. }
  7441. return false;
  7442. };
  7443. Observable.prototype._deferUnregister = function (observer) {
  7444. var _this = this;
  7445. observer.unregisterOnNextCall = false;
  7446. observer._willBeUnregistered = true;
  7447. BABYLON.Tools.SetImmediate(function () {
  7448. _this.remove(observer);
  7449. });
  7450. };
  7451. /**
  7452. * Notify all Observers by calling their respective callback with the given data
  7453. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7454. * @param eventData defines the data to send to all observers
  7455. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7456. * @param target defines the original target of the state
  7457. * @param currentTarget defines the current target of the state
  7458. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7459. */
  7460. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7461. if (mask === void 0) { mask = -1; }
  7462. if (!this._observers.length) {
  7463. return true;
  7464. }
  7465. var state = this._eventState;
  7466. state.mask = mask;
  7467. state.target = target;
  7468. state.currentTarget = currentTarget;
  7469. state.skipNextObservers = false;
  7470. state.lastReturnValue = eventData;
  7471. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7472. var obs = _a[_i];
  7473. if (obs._willBeUnregistered) {
  7474. continue;
  7475. }
  7476. if (obs.mask & mask) {
  7477. if (obs.scope) {
  7478. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7479. }
  7480. else {
  7481. state.lastReturnValue = obs.callback(eventData, state);
  7482. }
  7483. if (obs.unregisterOnNextCall) {
  7484. this._deferUnregister(obs);
  7485. }
  7486. }
  7487. if (state.skipNextObservers) {
  7488. return false;
  7489. }
  7490. }
  7491. return true;
  7492. };
  7493. /**
  7494. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7495. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7496. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7497. * and it is crucial that all callbacks will be executed.
  7498. * The order of the callbacks is kept, callbacks are not executed parallel.
  7499. *
  7500. * @param eventData The data to be sent to each callback
  7501. * @param mask is used to filter observers defaults to -1
  7502. * @param target defines the callback target (see EventState)
  7503. * @param currentTarget defines he current object in the bubbling phase
  7504. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7505. */
  7506. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7507. var _this = this;
  7508. if (mask === void 0) { mask = -1; }
  7509. // create an empty promise
  7510. var p = Promise.resolve(eventData);
  7511. // no observers? return this promise.
  7512. if (!this._observers.length) {
  7513. return p;
  7514. }
  7515. var state = this._eventState;
  7516. state.mask = mask;
  7517. state.target = target;
  7518. state.currentTarget = currentTarget;
  7519. state.skipNextObservers = false;
  7520. // execute one callback after another (not using Promise.all, the order is important)
  7521. this._observers.forEach(function (obs) {
  7522. if (state.skipNextObservers) {
  7523. return;
  7524. }
  7525. if (obs._willBeUnregistered) {
  7526. return;
  7527. }
  7528. if (obs.mask & mask) {
  7529. if (obs.scope) {
  7530. p = p.then(function (lastReturnedValue) {
  7531. state.lastReturnValue = lastReturnedValue;
  7532. return obs.callback.apply(obs.scope, [eventData, state]);
  7533. });
  7534. }
  7535. else {
  7536. p = p.then(function (lastReturnedValue) {
  7537. state.lastReturnValue = lastReturnedValue;
  7538. return obs.callback(eventData, state);
  7539. });
  7540. }
  7541. if (obs.unregisterOnNextCall) {
  7542. _this._deferUnregister(obs);
  7543. }
  7544. }
  7545. });
  7546. // return the eventData
  7547. return p.then(function () { return eventData; });
  7548. };
  7549. /**
  7550. * Notify a specific observer
  7551. * @param observer defines the observer to notify
  7552. * @param eventData defines the data to be sent to each callback
  7553. * @param mask is used to filter observers defaults to -1
  7554. */
  7555. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7556. if (mask === void 0) { mask = -1; }
  7557. var state = this._eventState;
  7558. state.mask = mask;
  7559. state.skipNextObservers = false;
  7560. observer.callback(eventData, state);
  7561. };
  7562. /**
  7563. * Gets a boolean indicating if the observable has at least one observer
  7564. * @returns true is the Observable has at least one Observer registered
  7565. */
  7566. Observable.prototype.hasObservers = function () {
  7567. return this._observers.length > 0;
  7568. };
  7569. /**
  7570. * Clear the list of observers
  7571. */
  7572. Observable.prototype.clear = function () {
  7573. this._observers = new Array();
  7574. this._onObserverAdded = null;
  7575. };
  7576. /**
  7577. * Clone the current observable
  7578. * @returns a new observable
  7579. */
  7580. Observable.prototype.clone = function () {
  7581. var result = new Observable();
  7582. result._observers = this._observers.slice(0);
  7583. return result;
  7584. };
  7585. /**
  7586. * Does this observable handles observer registered with a given mask
  7587. * @param mask defines the mask to be tested
  7588. * @return whether or not one observer registered with the given mask is handeled
  7589. **/
  7590. Observable.prototype.hasSpecificMask = function (mask) {
  7591. if (mask === void 0) { mask = -1; }
  7592. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7593. var obs = _a[_i];
  7594. if (obs.mask & mask || obs.mask === mask) {
  7595. return true;
  7596. }
  7597. }
  7598. return false;
  7599. };
  7600. return Observable;
  7601. }());
  7602. BABYLON.Observable = Observable;
  7603. })(BABYLON || (BABYLON = {}));
  7604. //# sourceMappingURL=babylon.observable.js.map
  7605. var BABYLON;
  7606. (function (BABYLON) {
  7607. var SmartArray = /** @class */ (function () {
  7608. function SmartArray(capacity) {
  7609. this.length = 0;
  7610. this.data = new Array(capacity);
  7611. this._id = SmartArray._GlobalId++;
  7612. }
  7613. SmartArray.prototype.push = function (value) {
  7614. this.data[this.length++] = value;
  7615. if (this.length > this.data.length) {
  7616. this.data.length *= 2;
  7617. }
  7618. };
  7619. SmartArray.prototype.forEach = function (func) {
  7620. for (var index = 0; index < this.length; index++) {
  7621. func(this.data[index]);
  7622. }
  7623. };
  7624. SmartArray.prototype.sort = function (compareFn) {
  7625. this.data.sort(compareFn);
  7626. };
  7627. SmartArray.prototype.reset = function () {
  7628. this.length = 0;
  7629. };
  7630. SmartArray.prototype.dispose = function () {
  7631. this.reset();
  7632. if (this.data) {
  7633. this.data.length = 0;
  7634. this.data = [];
  7635. }
  7636. };
  7637. SmartArray.prototype.concat = function (array) {
  7638. if (array.length === 0) {
  7639. return;
  7640. }
  7641. if (this.length + array.length > this.data.length) {
  7642. this.data.length = (this.length + array.length) * 2;
  7643. }
  7644. for (var index = 0; index < array.length; index++) {
  7645. this.data[this.length++] = (array.data || array)[index];
  7646. }
  7647. };
  7648. SmartArray.prototype.indexOf = function (value) {
  7649. var position = this.data.indexOf(value);
  7650. if (position >= this.length) {
  7651. return -1;
  7652. }
  7653. return position;
  7654. };
  7655. SmartArray.prototype.contains = function (value) {
  7656. return this.data.indexOf(value) !== -1;
  7657. };
  7658. // Statics
  7659. SmartArray._GlobalId = 0;
  7660. return SmartArray;
  7661. }());
  7662. BABYLON.SmartArray = SmartArray;
  7663. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7664. __extends(SmartArrayNoDuplicate, _super);
  7665. function SmartArrayNoDuplicate() {
  7666. var _this = _super !== null && _super.apply(this, arguments) || this;
  7667. _this._duplicateId = 0;
  7668. return _this;
  7669. }
  7670. SmartArrayNoDuplicate.prototype.push = function (value) {
  7671. _super.prototype.push.call(this, value);
  7672. if (!value.__smartArrayFlags) {
  7673. value.__smartArrayFlags = {};
  7674. }
  7675. value.__smartArrayFlags[this._id] = this._duplicateId;
  7676. };
  7677. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7678. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7679. return false;
  7680. }
  7681. this.push(value);
  7682. return true;
  7683. };
  7684. SmartArrayNoDuplicate.prototype.reset = function () {
  7685. _super.prototype.reset.call(this);
  7686. this._duplicateId++;
  7687. };
  7688. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7689. if (array.length === 0) {
  7690. return;
  7691. }
  7692. if (this.length + array.length > this.data.length) {
  7693. this.data.length = (this.length + array.length) * 2;
  7694. }
  7695. for (var index = 0; index < array.length; index++) {
  7696. var item = (array.data || array)[index];
  7697. this.pushNoDuplicate(item);
  7698. }
  7699. };
  7700. return SmartArrayNoDuplicate;
  7701. }(SmartArray));
  7702. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7703. })(BABYLON || (BABYLON = {}));
  7704. //# sourceMappingURL=babylon.smartArray.js.map
  7705. var BABYLON;
  7706. (function (BABYLON) {
  7707. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7708. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7709. var LoadFileError = /** @class */ (function (_super) {
  7710. __extends(LoadFileError, _super);
  7711. function LoadFileError(message, request) {
  7712. var _this = _super.call(this, message) || this;
  7713. _this.request = request;
  7714. _this.name = "LoadFileError";
  7715. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7716. return _this;
  7717. }
  7718. // Polyfill for Object.setPrototypeOf if necessary.
  7719. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7720. return LoadFileError;
  7721. }(Error));
  7722. BABYLON.LoadFileError = LoadFileError;
  7723. var RetryStrategy = /** @class */ (function () {
  7724. function RetryStrategy() {
  7725. }
  7726. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7727. if (maxRetries === void 0) { maxRetries = 3; }
  7728. if (baseInterval === void 0) { baseInterval = 500; }
  7729. return function (url, request, retryIndex) {
  7730. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7731. return -1;
  7732. }
  7733. return Math.pow(2, retryIndex) * baseInterval;
  7734. };
  7735. };
  7736. return RetryStrategy;
  7737. }());
  7738. BABYLON.RetryStrategy = RetryStrategy;
  7739. // Screenshots
  7740. var screenshotCanvas;
  7741. var cloneValue = function (source, destinationObject) {
  7742. if (!source)
  7743. return null;
  7744. if (source instanceof BABYLON.Mesh) {
  7745. return null;
  7746. }
  7747. if (source instanceof BABYLON.SubMesh) {
  7748. return source.clone(destinationObject);
  7749. }
  7750. else if (source.clone) {
  7751. return source.clone();
  7752. }
  7753. return null;
  7754. };
  7755. var Tools = /** @class */ (function () {
  7756. function Tools() {
  7757. }
  7758. /**
  7759. * Interpolates between a and b via alpha
  7760. * @param a The lower value (returned when alpha = 0)
  7761. * @param b The upper value (returned when alpha = 1)
  7762. * @param alpha The interpolation-factor
  7763. * @return The mixed value
  7764. */
  7765. Tools.Mix = function (a, b, alpha) {
  7766. return a * (1 - alpha) + b * alpha;
  7767. };
  7768. Tools.Instantiate = function (className) {
  7769. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7770. return Tools.RegisteredExternalClasses[className];
  7771. }
  7772. var arr = className.split(".");
  7773. var fn = (window || this);
  7774. for (var i = 0, len = arr.length; i < len; i++) {
  7775. fn = fn[arr[i]];
  7776. }
  7777. if (typeof fn !== "function") {
  7778. return null;
  7779. }
  7780. return fn;
  7781. };
  7782. /**
  7783. * Provides a slice function that will work even on IE
  7784. * @param data defines the array to slice
  7785. * @returns the new sliced array
  7786. */
  7787. Tools.Slice = function (data) {
  7788. if (data.slice) {
  7789. return data.slice();
  7790. }
  7791. return Array.prototype.slice.call(data);
  7792. };
  7793. Tools.SetImmediate = function (action) {
  7794. if (window.setImmediate) {
  7795. window.setImmediate(action);
  7796. }
  7797. else {
  7798. setTimeout(action, 1);
  7799. }
  7800. };
  7801. Tools.IsExponentOfTwo = function (value) {
  7802. var count = 1;
  7803. do {
  7804. count *= 2;
  7805. } while (count < value);
  7806. return count === value;
  7807. };
  7808. /**
  7809. * Find the next highest power of two.
  7810. * @param x Number to start search from.
  7811. * @return Next highest power of two.
  7812. */
  7813. Tools.CeilingPOT = function (x) {
  7814. x--;
  7815. x |= x >> 1;
  7816. x |= x >> 2;
  7817. x |= x >> 4;
  7818. x |= x >> 8;
  7819. x |= x >> 16;
  7820. x++;
  7821. return x;
  7822. };
  7823. /**
  7824. * Find the next lowest power of two.
  7825. * @param x Number to start search from.
  7826. * @return Next lowest power of two.
  7827. */
  7828. Tools.FloorPOT = function (x) {
  7829. x = x | (x >> 1);
  7830. x = x | (x >> 2);
  7831. x = x | (x >> 4);
  7832. x = x | (x >> 8);
  7833. x = x | (x >> 16);
  7834. return x - (x >> 1);
  7835. };
  7836. /**
  7837. * Find the nearest power of two.
  7838. * @param x Number to start search from.
  7839. * @return Next nearest power of two.
  7840. */
  7841. Tools.NearestPOT = function (x) {
  7842. var c = Tools.CeilingPOT(x);
  7843. var f = Tools.FloorPOT(x);
  7844. return (c - x) > (x - f) ? f : c;
  7845. };
  7846. Tools.GetExponentOfTwo = function (value, max, mode) {
  7847. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7848. var pot;
  7849. switch (mode) {
  7850. case BABYLON.Engine.SCALEMODE_FLOOR:
  7851. pot = Tools.FloorPOT(value);
  7852. break;
  7853. case BABYLON.Engine.SCALEMODE_NEAREST:
  7854. pot = Tools.NearestPOT(value);
  7855. break;
  7856. case BABYLON.Engine.SCALEMODE_CEILING:
  7857. default:
  7858. pot = Tools.CeilingPOT(value);
  7859. break;
  7860. }
  7861. return Math.min(pot, max);
  7862. };
  7863. Tools.GetFilename = function (path) {
  7864. var index = path.lastIndexOf("/");
  7865. if (index < 0)
  7866. return path;
  7867. return path.substring(index + 1);
  7868. };
  7869. /**
  7870. * Extracts the "folder" part of a path (everything before the filename).
  7871. * @param uri The URI to extract the info from
  7872. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7873. * @returns The "folder" part of the path
  7874. */
  7875. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7876. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7877. var index = uri.lastIndexOf("/");
  7878. if (index < 0) {
  7879. if (returnUnchangedIfNoSlash) {
  7880. return uri;
  7881. }
  7882. return "";
  7883. }
  7884. return uri.substring(0, index + 1);
  7885. };
  7886. Tools.GetDOMTextContent = function (element) {
  7887. var result = "";
  7888. var child = element.firstChild;
  7889. while (child) {
  7890. if (child.nodeType === 3) {
  7891. result += child.textContent;
  7892. }
  7893. child = child.nextSibling;
  7894. }
  7895. return result;
  7896. };
  7897. Tools.ToDegrees = function (angle) {
  7898. return angle * 180 / Math.PI;
  7899. };
  7900. Tools.ToRadians = function (angle) {
  7901. return angle * Math.PI / 180;
  7902. };
  7903. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7904. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7905. var output = "";
  7906. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7907. var i = 0;
  7908. var bytes = new Uint8Array(buffer);
  7909. while (i < bytes.length) {
  7910. chr1 = bytes[i++];
  7911. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7912. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7913. enc1 = chr1 >> 2;
  7914. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7915. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7916. enc4 = chr3 & 63;
  7917. if (isNaN(chr2)) {
  7918. enc3 = enc4 = 64;
  7919. }
  7920. else if (isNaN(chr3)) {
  7921. enc4 = 64;
  7922. }
  7923. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7924. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7925. }
  7926. return "data:image/png;base64," + output;
  7927. };
  7928. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7929. if (bias === void 0) { bias = null; }
  7930. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7931. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7932. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7933. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7934. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7935. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7936. }
  7937. if (bias) {
  7938. minimum.x -= minimum.x * bias.x + bias.y;
  7939. minimum.y -= minimum.y * bias.x + bias.y;
  7940. minimum.z -= minimum.z * bias.x + bias.y;
  7941. maximum.x += maximum.x * bias.x + bias.y;
  7942. maximum.y += maximum.y * bias.x + bias.y;
  7943. maximum.z += maximum.z * bias.x + bias.y;
  7944. }
  7945. return {
  7946. minimum: minimum,
  7947. maximum: maximum
  7948. };
  7949. };
  7950. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7951. if (bias === void 0) { bias = null; }
  7952. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7953. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7954. if (!stride) {
  7955. stride = 3;
  7956. }
  7957. for (var index = start; index < start + count; index++) {
  7958. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7959. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7960. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7961. }
  7962. if (bias) {
  7963. minimum.x -= minimum.x * bias.x + bias.y;
  7964. minimum.y -= minimum.y * bias.x + bias.y;
  7965. minimum.z -= minimum.z * bias.x + bias.y;
  7966. maximum.x += maximum.x * bias.x + bias.y;
  7967. maximum.y += maximum.y * bias.x + bias.y;
  7968. maximum.z += maximum.z * bias.x + bias.y;
  7969. }
  7970. return {
  7971. minimum: minimum,
  7972. maximum: maximum
  7973. };
  7974. };
  7975. Tools.Vector2ArrayFeeder = function (array) {
  7976. return function (index) {
  7977. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7978. var length = isFloatArray ? array.length / 2 : array.length;
  7979. if (index >= length) {
  7980. return null;
  7981. }
  7982. if (isFloatArray) {
  7983. var fa = array;
  7984. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7985. }
  7986. var a = array;
  7987. return a[index];
  7988. };
  7989. };
  7990. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7991. if (bias === void 0) { bias = null; }
  7992. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7993. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7994. var i = 0;
  7995. var cur = feeder(i++);
  7996. while (cur) {
  7997. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7998. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7999. cur = feeder(i++);
  8000. }
  8001. if (bias) {
  8002. minimum.x -= minimum.x * bias.x + bias.y;
  8003. minimum.y -= minimum.y * bias.x + bias.y;
  8004. maximum.x += maximum.x * bias.x + bias.y;
  8005. maximum.y += maximum.y * bias.x + bias.y;
  8006. }
  8007. return {
  8008. minimum: minimum,
  8009. maximum: maximum
  8010. };
  8011. };
  8012. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8013. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8014. return null;
  8015. return Array.isArray(obj) ? obj : [obj];
  8016. };
  8017. // Misc.
  8018. Tools.GetPointerPrefix = function () {
  8019. var eventPrefix = "pointer";
  8020. // Check if pointer events are supported
  8021. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8022. eventPrefix = "mouse";
  8023. }
  8024. return eventPrefix;
  8025. };
  8026. /**
  8027. * @param func - the function to be called
  8028. * @param requester - the object that will request the next frame. Falls back to window.
  8029. */
  8030. Tools.QueueNewFrame = function (func, requester) {
  8031. if (!Tools.IsWindowObjectExist()) {
  8032. return setTimeout(func, 16);
  8033. }
  8034. if (!requester) {
  8035. requester = window;
  8036. }
  8037. if (requester.requestAnimationFrame) {
  8038. return requester.requestAnimationFrame(func);
  8039. }
  8040. else if (requester.msRequestAnimationFrame) {
  8041. return requester.msRequestAnimationFrame(func);
  8042. }
  8043. else if (requester.webkitRequestAnimationFrame) {
  8044. return requester.webkitRequestAnimationFrame(func);
  8045. }
  8046. else if (requester.mozRequestAnimationFrame) {
  8047. return requester.mozRequestAnimationFrame(func);
  8048. }
  8049. else if (requester.oRequestAnimationFrame) {
  8050. return requester.oRequestAnimationFrame(func);
  8051. }
  8052. else {
  8053. return window.setTimeout(func, 16);
  8054. }
  8055. };
  8056. Tools.RequestFullscreen = function (element) {
  8057. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8058. if (!requestFunction)
  8059. return;
  8060. requestFunction.call(element);
  8061. };
  8062. Tools.ExitFullscreen = function () {
  8063. if (document.exitFullscreen) {
  8064. document.exitFullscreen();
  8065. }
  8066. else if (document.mozCancelFullScreen) {
  8067. document.mozCancelFullScreen();
  8068. }
  8069. else if (document.webkitCancelFullScreen) {
  8070. document.webkitCancelFullScreen();
  8071. }
  8072. else if (document.msCancelFullScreen) {
  8073. document.msCancelFullScreen();
  8074. }
  8075. };
  8076. Tools.SetCorsBehavior = function (url, element) {
  8077. if (url && url.indexOf("data:") === 0) {
  8078. return;
  8079. }
  8080. if (Tools.CorsBehavior) {
  8081. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8082. element.crossOrigin = Tools.CorsBehavior;
  8083. }
  8084. else {
  8085. var result = Tools.CorsBehavior(url);
  8086. if (result) {
  8087. element.crossOrigin = result;
  8088. }
  8089. }
  8090. }
  8091. };
  8092. // External files
  8093. Tools.CleanUrl = function (url) {
  8094. url = url.replace(/#/mg, "%23");
  8095. return url;
  8096. };
  8097. Tools.LoadImage = function (url, onLoad, onError, database) {
  8098. if (url instanceof ArrayBuffer) {
  8099. url = Tools.EncodeArrayBufferTobase64(url);
  8100. }
  8101. url = Tools.CleanUrl(url);
  8102. url = Tools.PreprocessUrl(url);
  8103. var img = new Image();
  8104. Tools.SetCorsBehavior(url, img);
  8105. var loadHandler = function () {
  8106. img.removeEventListener("load", loadHandler);
  8107. img.removeEventListener("error", errorHandler);
  8108. onLoad(img);
  8109. };
  8110. var errorHandler = function (err) {
  8111. img.removeEventListener("load", loadHandler);
  8112. img.removeEventListener("error", errorHandler);
  8113. Tools.Error("Error while trying to load image: " + url);
  8114. if (onError) {
  8115. onError("Error while trying to load image: " + url, err);
  8116. }
  8117. };
  8118. img.addEventListener("load", loadHandler);
  8119. img.addEventListener("error", errorHandler);
  8120. var noIndexedDB = function () {
  8121. img.src = url;
  8122. };
  8123. var loadFromIndexedDB = function () {
  8124. if (database) {
  8125. database.loadImageFromDB(url, img);
  8126. }
  8127. };
  8128. //ANY database to do!
  8129. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8130. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8131. }
  8132. else {
  8133. if (url.indexOf("file:") !== -1) {
  8134. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8135. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8136. try {
  8137. var blobURL;
  8138. try {
  8139. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8140. }
  8141. catch (ex) {
  8142. // Chrome doesn't support oneTimeOnly parameter
  8143. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8144. }
  8145. img.src = blobURL;
  8146. }
  8147. catch (e) {
  8148. img.src = "";
  8149. }
  8150. return img;
  8151. }
  8152. }
  8153. noIndexedDB();
  8154. }
  8155. return img;
  8156. };
  8157. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8158. url = Tools.CleanUrl(url);
  8159. url = Tools.PreprocessUrl(url);
  8160. // If file and file input are set
  8161. if (url.indexOf("file:") !== -1) {
  8162. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8163. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8164. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8165. }
  8166. }
  8167. var loadUrl = Tools.BaseUrl + url;
  8168. var aborted = false;
  8169. var fileRequest = {
  8170. onCompleteObservable: new BABYLON.Observable(),
  8171. abort: function () { return aborted = true; },
  8172. };
  8173. var requestFile = function () {
  8174. var request = new XMLHttpRequest();
  8175. var retryHandle = null;
  8176. fileRequest.abort = function () {
  8177. aborted = true;
  8178. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8179. request.abort();
  8180. }
  8181. if (retryHandle !== null) {
  8182. clearTimeout(retryHandle);
  8183. retryHandle = null;
  8184. }
  8185. };
  8186. var retryLoop = function (retryIndex) {
  8187. request.open('GET', loadUrl, true);
  8188. if (useArrayBuffer) {
  8189. request.responseType = "arraybuffer";
  8190. }
  8191. if (onProgress) {
  8192. request.addEventListener("progress", onProgress);
  8193. }
  8194. var onLoadEnd = function () {
  8195. request.removeEventListener("loadend", onLoadEnd);
  8196. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8197. fileRequest.onCompleteObservable.clear();
  8198. };
  8199. request.addEventListener("loadend", onLoadEnd);
  8200. var onReadyStateChange = function () {
  8201. if (aborted) {
  8202. return;
  8203. }
  8204. // In case of undefined state in some browsers.
  8205. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8206. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8207. request.removeEventListener("readystatechange", onReadyStateChange);
  8208. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8209. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8210. return;
  8211. }
  8212. var retryStrategy = Tools.DefaultRetryStrategy;
  8213. if (retryStrategy) {
  8214. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8215. if (waitTime !== -1) {
  8216. // Prevent the request from completing for retry.
  8217. request.removeEventListener("loadend", onLoadEnd);
  8218. request = new XMLHttpRequest();
  8219. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8220. return;
  8221. }
  8222. }
  8223. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8224. if (onError) {
  8225. onError(request, e);
  8226. }
  8227. else {
  8228. throw e;
  8229. }
  8230. }
  8231. };
  8232. request.addEventListener("readystatechange", onReadyStateChange);
  8233. request.send();
  8234. };
  8235. retryLoop(0);
  8236. };
  8237. // Caching all files
  8238. if (database && database.enableSceneOffline) {
  8239. var noIndexedDB_1 = function () {
  8240. if (!aborted) {
  8241. requestFile();
  8242. }
  8243. };
  8244. var loadFromIndexedDB = function () {
  8245. // TODO: database needs to support aborting and should return a IFileRequest
  8246. if (aborted) {
  8247. return;
  8248. }
  8249. if (database) {
  8250. database.loadFileFromDB(url, function (data) {
  8251. if (!aborted) {
  8252. onSuccess(data);
  8253. }
  8254. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8255. }, onProgress ? function (event) {
  8256. if (!aborted) {
  8257. onProgress(event);
  8258. }
  8259. } : undefined, noIndexedDB_1, useArrayBuffer);
  8260. }
  8261. };
  8262. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8263. }
  8264. else {
  8265. requestFile();
  8266. }
  8267. return fileRequest;
  8268. };
  8269. /**
  8270. * Load a script (identified by an url). When the url returns, the
  8271. * content of this file is added into a new script element, attached to the DOM (body element)
  8272. */
  8273. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8274. var head = document.getElementsByTagName('head')[0];
  8275. var script = document.createElement('script');
  8276. script.type = 'text/javascript';
  8277. script.src = scriptUrl;
  8278. script.onload = function () {
  8279. if (onSuccess) {
  8280. onSuccess();
  8281. }
  8282. };
  8283. script.onerror = function (e) {
  8284. if (onError) {
  8285. onError("Unable to load script", e);
  8286. }
  8287. };
  8288. head.appendChild(script);
  8289. };
  8290. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8291. var reader = new FileReader();
  8292. var request = {
  8293. onCompleteObservable: new BABYLON.Observable(),
  8294. abort: function () { return reader.abort(); },
  8295. };
  8296. reader.onloadend = function (e) {
  8297. request.onCompleteObservable.notifyObservers(request);
  8298. };
  8299. reader.onload = function (e) {
  8300. //target doesn't have result from ts 1.3
  8301. callback(e.target['result']);
  8302. };
  8303. reader.onprogress = progressCallback;
  8304. reader.readAsDataURL(fileToLoad);
  8305. return request;
  8306. };
  8307. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8308. var reader = new FileReader();
  8309. var request = {
  8310. onCompleteObservable: new BABYLON.Observable(),
  8311. abort: function () { return reader.abort(); },
  8312. };
  8313. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8314. reader.onerror = function (e) {
  8315. Tools.Log("Error while reading file: " + fileToLoad.name);
  8316. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8317. };
  8318. reader.onload = function (e) {
  8319. //target doesn't have result from ts 1.3
  8320. callback(e.target['result']);
  8321. };
  8322. if (progressCallBack) {
  8323. reader.onprogress = progressCallBack;
  8324. }
  8325. if (!useArrayBuffer) {
  8326. // Asynchronous read
  8327. reader.readAsText(fileToLoad);
  8328. }
  8329. else {
  8330. reader.readAsArrayBuffer(fileToLoad);
  8331. }
  8332. return request;
  8333. };
  8334. //returns a downloadable url to a file content.
  8335. Tools.FileAsURL = function (content) {
  8336. var fileBlob = new Blob([content]);
  8337. var url = window.URL || window.webkitURL;
  8338. var link = url.createObjectURL(fileBlob);
  8339. return link;
  8340. };
  8341. // Misc.
  8342. Tools.Format = function (value, decimals) {
  8343. if (decimals === void 0) { decimals = 2; }
  8344. return value.toFixed(decimals);
  8345. };
  8346. Tools.CheckExtends = function (v, min, max) {
  8347. if (v.x < min.x)
  8348. min.x = v.x;
  8349. if (v.y < min.y)
  8350. min.y = v.y;
  8351. if (v.z < min.z)
  8352. min.z = v.z;
  8353. if (v.x > max.x)
  8354. max.x = v.x;
  8355. if (v.y > max.y)
  8356. max.y = v.y;
  8357. if (v.z > max.z)
  8358. max.z = v.z;
  8359. };
  8360. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8361. for (var prop in source) {
  8362. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8363. continue;
  8364. }
  8365. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8366. continue;
  8367. }
  8368. var sourceValue = source[prop];
  8369. var typeOfSourceValue = typeof sourceValue;
  8370. if (typeOfSourceValue === "function") {
  8371. continue;
  8372. }
  8373. if (typeOfSourceValue === "object") {
  8374. if (sourceValue instanceof Array) {
  8375. destination[prop] = [];
  8376. if (sourceValue.length > 0) {
  8377. if (typeof sourceValue[0] == "object") {
  8378. for (var index = 0; index < sourceValue.length; index++) {
  8379. var clonedValue = cloneValue(sourceValue[index], destination);
  8380. if (destination[prop].indexOf(clonedValue) === -1) {
  8381. destination[prop].push(clonedValue);
  8382. }
  8383. }
  8384. }
  8385. else {
  8386. destination[prop] = sourceValue.slice(0);
  8387. }
  8388. }
  8389. }
  8390. else {
  8391. destination[prop] = cloneValue(sourceValue, destination);
  8392. }
  8393. }
  8394. else {
  8395. destination[prop] = sourceValue;
  8396. }
  8397. }
  8398. };
  8399. Tools.IsEmpty = function (obj) {
  8400. for (var i in obj) {
  8401. if (obj.hasOwnProperty(i)) {
  8402. return false;
  8403. }
  8404. }
  8405. return true;
  8406. };
  8407. Tools.RegisterTopRootEvents = function (events) {
  8408. for (var index = 0; index < events.length; index++) {
  8409. var event = events[index];
  8410. window.addEventListener(event.name, event.handler, false);
  8411. try {
  8412. if (window.parent) {
  8413. window.parent.addEventListener(event.name, event.handler, false);
  8414. }
  8415. }
  8416. catch (e) {
  8417. // Silently fails...
  8418. }
  8419. }
  8420. };
  8421. Tools.UnregisterTopRootEvents = function (events) {
  8422. for (var index = 0; index < events.length; index++) {
  8423. var event = events[index];
  8424. window.removeEventListener(event.name, event.handler);
  8425. try {
  8426. if (window.parent) {
  8427. window.parent.removeEventListener(event.name, event.handler);
  8428. }
  8429. }
  8430. catch (e) {
  8431. // Silently fails...
  8432. }
  8433. }
  8434. };
  8435. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8436. if (mimeType === void 0) { mimeType = "image/png"; }
  8437. // Read the contents of the framebuffer
  8438. var numberOfChannelsByLine = width * 4;
  8439. var halfHeight = height / 2;
  8440. //Reading datas from WebGL
  8441. var data = engine.readPixels(0, 0, width, height);
  8442. //To flip image on Y axis.
  8443. for (var i = 0; i < halfHeight; i++) {
  8444. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8445. var currentCell = j + i * numberOfChannelsByLine;
  8446. var targetLine = height - i - 1;
  8447. var targetCell = j + targetLine * numberOfChannelsByLine;
  8448. var temp = data[currentCell];
  8449. data[currentCell] = data[targetCell];
  8450. data[targetCell] = temp;
  8451. }
  8452. }
  8453. // Create a 2D canvas to store the result
  8454. if (!screenshotCanvas) {
  8455. screenshotCanvas = document.createElement('canvas');
  8456. }
  8457. screenshotCanvas.width = width;
  8458. screenshotCanvas.height = height;
  8459. var context = screenshotCanvas.getContext('2d');
  8460. if (context) {
  8461. // Copy the pixels to a 2D canvas
  8462. var imageData = context.createImageData(width, height);
  8463. var castData = (imageData.data);
  8464. castData.set(data);
  8465. context.putImageData(imageData, 0, 0);
  8466. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8467. }
  8468. };
  8469. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8470. if (mimeType === void 0) { mimeType = "image/png"; }
  8471. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8472. if (successCallback) {
  8473. successCallback(base64Image);
  8474. }
  8475. else {
  8476. // We need HTMLCanvasElement.toBlob for HD screenshots
  8477. if (!screenshotCanvas.toBlob) {
  8478. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8479. screenshotCanvas.toBlob = function (callback, type, quality) {
  8480. var _this = this;
  8481. setTimeout(function () {
  8482. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8483. for (var i = 0; i < len; i++) {
  8484. arr[i] = binStr.charCodeAt(i);
  8485. }
  8486. callback(new Blob([arr], { type: type || 'image/png' }));
  8487. });
  8488. };
  8489. }
  8490. screenshotCanvas.toBlob(function (blob) {
  8491. var url = URL.createObjectURL(blob);
  8492. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8493. if (("download" in document.createElement("a"))) {
  8494. var a = window.document.createElement("a");
  8495. a.href = url;
  8496. if (fileName) {
  8497. a.setAttribute("download", fileName);
  8498. }
  8499. else {
  8500. var date = new Date();
  8501. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8502. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8503. }
  8504. window.document.body.appendChild(a);
  8505. a.addEventListener("click", function () {
  8506. if (a.parentElement) {
  8507. a.parentElement.removeChild(a);
  8508. }
  8509. });
  8510. a.click();
  8511. }
  8512. else {
  8513. var newWindow = window.open("");
  8514. if (!newWindow)
  8515. return;
  8516. var img = newWindow.document.createElement("img");
  8517. img.onload = function () {
  8518. // no longer need to read the blob so it's revoked
  8519. URL.revokeObjectURL(url);
  8520. };
  8521. img.src = url;
  8522. newWindow.document.body.appendChild(img);
  8523. }
  8524. });
  8525. }
  8526. };
  8527. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8528. if (mimeType === void 0) { mimeType = "image/png"; }
  8529. var width;
  8530. var height;
  8531. // If a precision value is specified
  8532. if (size.precision) {
  8533. width = Math.round(engine.getRenderWidth() * size.precision);
  8534. height = Math.round(width / engine.getAspectRatio(camera));
  8535. }
  8536. else if (size.width && size.height) {
  8537. width = size.width;
  8538. height = size.height;
  8539. }
  8540. else if (size.width && !size.height) {
  8541. width = size.width;
  8542. height = Math.round(width / engine.getAspectRatio(camera));
  8543. }
  8544. else if (size.height && !size.width) {
  8545. height = size.height;
  8546. width = Math.round(height * engine.getAspectRatio(camera));
  8547. }
  8548. else if (!isNaN(size)) {
  8549. height = size;
  8550. width = size;
  8551. }
  8552. else {
  8553. Tools.Error("Invalid 'size' parameter !");
  8554. return;
  8555. }
  8556. if (!screenshotCanvas) {
  8557. screenshotCanvas = document.createElement('canvas');
  8558. }
  8559. screenshotCanvas.width = width;
  8560. screenshotCanvas.height = height;
  8561. var renderContext = screenshotCanvas.getContext("2d");
  8562. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8563. var newWidth = width;
  8564. var newHeight = newWidth / ratio;
  8565. if (newHeight > height) {
  8566. newHeight = height;
  8567. newWidth = newHeight * ratio;
  8568. }
  8569. var offsetX = Math.max(0, width - newWidth) / 2;
  8570. var offsetY = Math.max(0, height - newHeight) / 2;
  8571. var renderingCanvas = engine.getRenderingCanvas();
  8572. if (renderContext && renderingCanvas) {
  8573. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8574. }
  8575. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8576. };
  8577. /**
  8578. * Generates an image screenshot from the specified camera.
  8579. *
  8580. * @param engine The engine to use for rendering
  8581. * @param camera The camera to use for rendering
  8582. * @param size This parameter can be set to a single number or to an object with the
  8583. * following (optional) properties: precision, width, height. If a single number is passed,
  8584. * it will be used for both width and height. If an object is passed, the screenshot size
  8585. * will be derived from the parameters. The precision property is a multiplier allowing
  8586. * rendering at a higher or lower resolution.
  8587. * @param successCallback The callback receives a single parameter which contains the
  8588. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8589. * src parameter of an <img> to display it.
  8590. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8591. * Check your browser for supported MIME types.
  8592. * @param samples Texture samples (default: 1)
  8593. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8594. * @param fileName A name for for the downloaded file.
  8595. * @constructor
  8596. */
  8597. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8598. if (mimeType === void 0) { mimeType = "image/png"; }
  8599. if (samples === void 0) { samples = 1; }
  8600. if (antialiasing === void 0) { antialiasing = false; }
  8601. var width;
  8602. var height;
  8603. //If a precision value is specified
  8604. if (size.precision) {
  8605. width = Math.round(engine.getRenderWidth() * size.precision);
  8606. height = Math.round(width / engine.getAspectRatio(camera));
  8607. size = { width: width, height: height };
  8608. }
  8609. else if (size.width && size.height) {
  8610. width = size.width;
  8611. height = size.height;
  8612. }
  8613. else if (size.width && !size.height) {
  8614. width = size.width;
  8615. height = Math.round(width / engine.getAspectRatio(camera));
  8616. size = { width: width, height: height };
  8617. }
  8618. else if (size.height && !size.width) {
  8619. height = size.height;
  8620. width = Math.round(height * engine.getAspectRatio(camera));
  8621. size = { width: width, height: height };
  8622. }
  8623. else if (!isNaN(size)) {
  8624. height = size;
  8625. width = size;
  8626. }
  8627. else {
  8628. Tools.Error("Invalid 'size' parameter !");
  8629. return;
  8630. }
  8631. var scene = camera.getScene();
  8632. var previousCamera = null;
  8633. if (scene.activeCamera !== camera) {
  8634. previousCamera = scene.activeCamera;
  8635. scene.activeCamera = camera;
  8636. }
  8637. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8638. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8639. texture.renderList = null;
  8640. texture.samples = samples;
  8641. if (antialiasing) {
  8642. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8643. }
  8644. texture.onAfterRenderObservable.add(function () {
  8645. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8646. });
  8647. scene.incrementRenderId();
  8648. scene.resetCachedMaterial();
  8649. texture.render(true);
  8650. texture.dispose();
  8651. if (previousCamera) {
  8652. scene.activeCamera = previousCamera;
  8653. }
  8654. camera.getProjectionMatrix(true); // Force cache refresh;
  8655. };
  8656. // XHR response validator for local file scenario
  8657. Tools.ValidateXHRData = function (xhr, dataType) {
  8658. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8659. if (dataType === void 0) { dataType = 7; }
  8660. try {
  8661. if (dataType & 1) {
  8662. if (xhr.responseText && xhr.responseText.length > 0) {
  8663. return true;
  8664. }
  8665. else if (dataType === 1) {
  8666. return false;
  8667. }
  8668. }
  8669. if (dataType & 2) {
  8670. // Check header width and height since there is no "TGA" magic number
  8671. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8672. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8673. return true;
  8674. }
  8675. else if (dataType === 2) {
  8676. return false;
  8677. }
  8678. }
  8679. if (dataType & 4) {
  8680. // Check for the "DDS" magic number
  8681. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8682. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8683. return true;
  8684. }
  8685. else {
  8686. return false;
  8687. }
  8688. }
  8689. }
  8690. catch (e) {
  8691. // Global protection
  8692. }
  8693. return false;
  8694. };
  8695. /**
  8696. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8697. * Be aware Math.random() could cause collisions, but:
  8698. * "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"
  8699. */
  8700. Tools.RandomId = function () {
  8701. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8702. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8703. return v.toString(16);
  8704. });
  8705. };
  8706. /**
  8707. * Test if the given uri is a base64 string.
  8708. * @param uri The uri to test
  8709. * @return True if the uri is a base64 string or false otherwise.
  8710. */
  8711. Tools.IsBase64 = function (uri) {
  8712. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8713. };
  8714. /**
  8715. * Decode the given base64 uri.
  8716. * @param uri The uri to decode
  8717. * @return The decoded base64 data.
  8718. */
  8719. Tools.DecodeBase64 = function (uri) {
  8720. var decodedString = atob(uri.split(",")[1]);
  8721. var bufferLength = decodedString.length;
  8722. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8723. for (var i = 0; i < bufferLength; i++) {
  8724. bufferView[i] = decodedString.charCodeAt(i);
  8725. }
  8726. return bufferView.buffer;
  8727. };
  8728. Object.defineProperty(Tools, "NoneLogLevel", {
  8729. get: function () {
  8730. return Tools._NoneLogLevel;
  8731. },
  8732. enumerable: true,
  8733. configurable: true
  8734. });
  8735. Object.defineProperty(Tools, "MessageLogLevel", {
  8736. get: function () {
  8737. return Tools._MessageLogLevel;
  8738. },
  8739. enumerable: true,
  8740. configurable: true
  8741. });
  8742. Object.defineProperty(Tools, "WarningLogLevel", {
  8743. get: function () {
  8744. return Tools._WarningLogLevel;
  8745. },
  8746. enumerable: true,
  8747. configurable: true
  8748. });
  8749. Object.defineProperty(Tools, "ErrorLogLevel", {
  8750. get: function () {
  8751. return Tools._ErrorLogLevel;
  8752. },
  8753. enumerable: true,
  8754. configurable: true
  8755. });
  8756. Object.defineProperty(Tools, "AllLogLevel", {
  8757. get: function () {
  8758. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8759. },
  8760. enumerable: true,
  8761. configurable: true
  8762. });
  8763. Tools._AddLogEntry = function (entry) {
  8764. Tools._LogCache = entry + Tools._LogCache;
  8765. if (Tools.OnNewCacheEntry) {
  8766. Tools.OnNewCacheEntry(entry);
  8767. }
  8768. };
  8769. Tools._FormatMessage = function (message) {
  8770. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8771. var date = new Date();
  8772. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8773. };
  8774. Tools._LogDisabled = function (message) {
  8775. // nothing to do
  8776. };
  8777. Tools._LogEnabled = function (message) {
  8778. var formattedMessage = Tools._FormatMessage(message);
  8779. console.log("BJS - " + formattedMessage);
  8780. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8781. Tools._AddLogEntry(entry);
  8782. };
  8783. Tools._WarnDisabled = function (message) {
  8784. // nothing to do
  8785. };
  8786. Tools._WarnEnabled = function (message) {
  8787. var formattedMessage = Tools._FormatMessage(message);
  8788. console.warn("BJS - " + formattedMessage);
  8789. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8790. Tools._AddLogEntry(entry);
  8791. };
  8792. Tools._ErrorDisabled = function (message) {
  8793. // nothing to do
  8794. };
  8795. Tools._ErrorEnabled = function (message) {
  8796. Tools.errorsCount++;
  8797. var formattedMessage = Tools._FormatMessage(message);
  8798. console.error("BJS - " + formattedMessage);
  8799. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8800. Tools._AddLogEntry(entry);
  8801. };
  8802. Object.defineProperty(Tools, "LogCache", {
  8803. get: function () {
  8804. return Tools._LogCache;
  8805. },
  8806. enumerable: true,
  8807. configurable: true
  8808. });
  8809. Tools.ClearLogCache = function () {
  8810. Tools._LogCache = "";
  8811. Tools.errorsCount = 0;
  8812. };
  8813. Object.defineProperty(Tools, "LogLevels", {
  8814. set: function (level) {
  8815. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8816. Tools.Log = Tools._LogEnabled;
  8817. }
  8818. else {
  8819. Tools.Log = Tools._LogDisabled;
  8820. }
  8821. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8822. Tools.Warn = Tools._WarnEnabled;
  8823. }
  8824. else {
  8825. Tools.Warn = Tools._WarnDisabled;
  8826. }
  8827. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8828. Tools.Error = Tools._ErrorEnabled;
  8829. }
  8830. else {
  8831. Tools.Error = Tools._ErrorDisabled;
  8832. }
  8833. },
  8834. enumerable: true,
  8835. configurable: true
  8836. });
  8837. Tools.IsWindowObjectExist = function () {
  8838. return (typeof window) !== "undefined";
  8839. };
  8840. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8841. get: function () {
  8842. return Tools._PerformanceNoneLogLevel;
  8843. },
  8844. enumerable: true,
  8845. configurable: true
  8846. });
  8847. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8848. get: function () {
  8849. return Tools._PerformanceUserMarkLogLevel;
  8850. },
  8851. enumerable: true,
  8852. configurable: true
  8853. });
  8854. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8855. get: function () {
  8856. return Tools._PerformanceConsoleLogLevel;
  8857. },
  8858. enumerable: true,
  8859. configurable: true
  8860. });
  8861. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8862. set: function (level) {
  8863. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8864. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8865. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8866. return;
  8867. }
  8868. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8869. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8870. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8871. return;
  8872. }
  8873. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8874. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8875. },
  8876. enumerable: true,
  8877. configurable: true
  8878. });
  8879. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8880. };
  8881. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8882. };
  8883. Tools._StartUserMark = function (counterName, condition) {
  8884. if (condition === void 0) { condition = true; }
  8885. if (!Tools._performance) {
  8886. if (!Tools.IsWindowObjectExist()) {
  8887. return;
  8888. }
  8889. Tools._performance = window.performance;
  8890. }
  8891. if (!condition || !Tools._performance.mark) {
  8892. return;
  8893. }
  8894. Tools._performance.mark(counterName + "-Begin");
  8895. };
  8896. Tools._EndUserMark = function (counterName, condition) {
  8897. if (condition === void 0) { condition = true; }
  8898. if (!condition || !Tools._performance.mark) {
  8899. return;
  8900. }
  8901. Tools._performance.mark(counterName + "-End");
  8902. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8903. };
  8904. Tools._StartPerformanceConsole = function (counterName, condition) {
  8905. if (condition === void 0) { condition = true; }
  8906. if (!condition) {
  8907. return;
  8908. }
  8909. Tools._StartUserMark(counterName, condition);
  8910. if (console.time) {
  8911. console.time(counterName);
  8912. }
  8913. };
  8914. Tools._EndPerformanceConsole = function (counterName, condition) {
  8915. if (condition === void 0) { condition = true; }
  8916. if (!condition) {
  8917. return;
  8918. }
  8919. Tools._EndUserMark(counterName, condition);
  8920. if (console.time) {
  8921. console.timeEnd(counterName);
  8922. }
  8923. };
  8924. Object.defineProperty(Tools, "Now", {
  8925. get: function () {
  8926. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8927. return window.performance.now();
  8928. }
  8929. return new Date().getTime();
  8930. },
  8931. enumerable: true,
  8932. configurable: true
  8933. });
  8934. /**
  8935. * This method will return the name of the class used to create the instance of the given object.
  8936. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8937. * @param object the object to get the class name from
  8938. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8939. */
  8940. Tools.GetClassName = function (object, isType) {
  8941. if (isType === void 0) { isType = false; }
  8942. var name = null;
  8943. if (!isType && object.getClassName) {
  8944. name = object.getClassName();
  8945. }
  8946. else {
  8947. if (object instanceof Object) {
  8948. var classObj = isType ? object : Object.getPrototypeOf(object);
  8949. name = classObj.constructor["__bjsclassName__"];
  8950. }
  8951. if (!name) {
  8952. name = typeof object;
  8953. }
  8954. }
  8955. return name;
  8956. };
  8957. Tools.First = function (array, predicate) {
  8958. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8959. var el = array_1[_i];
  8960. if (predicate(el)) {
  8961. return el;
  8962. }
  8963. }
  8964. return null;
  8965. };
  8966. /**
  8967. * This method will return the name of the full name of the class, including its owning module (if any).
  8968. * 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).
  8969. * @param object the object to get the class name from
  8970. * @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.
  8971. */
  8972. Tools.getFullClassName = function (object, isType) {
  8973. if (isType === void 0) { isType = false; }
  8974. var className = null;
  8975. var moduleName = null;
  8976. if (!isType && object.getClassName) {
  8977. className = object.getClassName();
  8978. }
  8979. else {
  8980. if (object instanceof Object) {
  8981. var classObj = isType ? object : Object.getPrototypeOf(object);
  8982. className = classObj.constructor["__bjsclassName__"];
  8983. moduleName = classObj.constructor["__bjsmoduleName__"];
  8984. }
  8985. if (!className) {
  8986. className = typeof object;
  8987. }
  8988. }
  8989. if (!className) {
  8990. return null;
  8991. }
  8992. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8993. };
  8994. /**
  8995. * 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.
  8996. * @param array
  8997. */
  8998. Tools.arrayOrStringFeeder = function (array) {
  8999. return function (index) {
  9000. if (index >= array.length) {
  9001. return null;
  9002. }
  9003. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9004. if (val && val.getHashCode) {
  9005. val = val.getHashCode();
  9006. }
  9007. if (typeof val === "string") {
  9008. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9009. }
  9010. return val;
  9011. };
  9012. };
  9013. /**
  9014. * Compute the hashCode of a stream of number
  9015. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9016. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9017. * @return the hash code computed
  9018. */
  9019. Tools.hashCodeFromStream = function (feeder) {
  9020. // Based from here: http://stackoverflow.com/a/7616484/802124
  9021. var hash = 0;
  9022. var index = 0;
  9023. var chr = feeder(index++);
  9024. while (chr != null) {
  9025. hash = ((hash << 5) - hash) + chr;
  9026. hash |= 0; // Convert to 32bit integer
  9027. chr = feeder(index++);
  9028. }
  9029. return hash;
  9030. };
  9031. /**
  9032. * Returns a promise that resolves after the given amount of time.
  9033. * @param delay Number of milliseconds to delay
  9034. * @returns Promise that resolves after the given amount of time
  9035. */
  9036. Tools.DelayAsync = function (delay) {
  9037. return new Promise(function (resolve) {
  9038. setTimeout(function () {
  9039. resolve();
  9040. }, delay);
  9041. });
  9042. };
  9043. Tools.BaseUrl = "";
  9044. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9045. /**
  9046. * Default behaviour for cors in the application.
  9047. * It can be a string if the expected behavior is identical in the entire app.
  9048. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9049. */
  9050. Tools.CorsBehavior = "anonymous";
  9051. Tools.UseFallbackTexture = true;
  9052. /**
  9053. * Use this object to register external classes like custom textures or material
  9054. * to allow the laoders to instantiate them
  9055. */
  9056. Tools.RegisteredExternalClasses = {};
  9057. // Used in case of a texture loading problem
  9058. 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";
  9059. Tools.PreprocessUrl = function (url) {
  9060. return url;
  9061. };
  9062. // Logs
  9063. Tools._NoneLogLevel = 0;
  9064. Tools._MessageLogLevel = 1;
  9065. Tools._WarningLogLevel = 2;
  9066. Tools._ErrorLogLevel = 4;
  9067. Tools._LogCache = "";
  9068. Tools.errorsCount = 0;
  9069. Tools.Log = Tools._LogEnabled;
  9070. Tools.Warn = Tools._WarnEnabled;
  9071. Tools.Error = Tools._ErrorEnabled;
  9072. // Performances
  9073. Tools._PerformanceNoneLogLevel = 0;
  9074. Tools._PerformanceUserMarkLogLevel = 1;
  9075. Tools._PerformanceConsoleLogLevel = 2;
  9076. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9077. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9078. return Tools;
  9079. }());
  9080. BABYLON.Tools = Tools;
  9081. /**
  9082. * This class is used to track a performance counter which is number based.
  9083. * The user has access to many properties which give statistics of different nature
  9084. *
  9085. * The implementer can track two kinds of Performance Counter: time and count
  9086. * 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.
  9087. * 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.
  9088. */
  9089. var PerfCounter = /** @class */ (function () {
  9090. function PerfCounter() {
  9091. this._startMonitoringTime = 0;
  9092. this._min = 0;
  9093. this._max = 0;
  9094. this._average = 0;
  9095. this._lastSecAverage = 0;
  9096. this._current = 0;
  9097. this._totalValueCount = 0;
  9098. this._totalAccumulated = 0;
  9099. this._lastSecAccumulated = 0;
  9100. this._lastSecTime = 0;
  9101. this._lastSecValueCount = 0;
  9102. }
  9103. Object.defineProperty(PerfCounter.prototype, "min", {
  9104. /**
  9105. * Returns the smallest value ever
  9106. */
  9107. get: function () {
  9108. return this._min;
  9109. },
  9110. enumerable: true,
  9111. configurable: true
  9112. });
  9113. Object.defineProperty(PerfCounter.prototype, "max", {
  9114. /**
  9115. * Returns the biggest value ever
  9116. */
  9117. get: function () {
  9118. return this._max;
  9119. },
  9120. enumerable: true,
  9121. configurable: true
  9122. });
  9123. Object.defineProperty(PerfCounter.prototype, "average", {
  9124. /**
  9125. * Returns the average value since the performance counter is running
  9126. */
  9127. get: function () {
  9128. return this._average;
  9129. },
  9130. enumerable: true,
  9131. configurable: true
  9132. });
  9133. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9134. /**
  9135. * Returns the average value of the last second the counter was monitored
  9136. */
  9137. get: function () {
  9138. return this._lastSecAverage;
  9139. },
  9140. enumerable: true,
  9141. configurable: true
  9142. });
  9143. Object.defineProperty(PerfCounter.prototype, "current", {
  9144. /**
  9145. * Returns the current value
  9146. */
  9147. get: function () {
  9148. return this._current;
  9149. },
  9150. enumerable: true,
  9151. configurable: true
  9152. });
  9153. Object.defineProperty(PerfCounter.prototype, "total", {
  9154. get: function () {
  9155. return this._totalAccumulated;
  9156. },
  9157. enumerable: true,
  9158. configurable: true
  9159. });
  9160. Object.defineProperty(PerfCounter.prototype, "count", {
  9161. get: function () {
  9162. return this._totalValueCount;
  9163. },
  9164. enumerable: true,
  9165. configurable: true
  9166. });
  9167. /**
  9168. * Call this method to start monitoring a new frame.
  9169. * 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.
  9170. */
  9171. PerfCounter.prototype.fetchNewFrame = function () {
  9172. this._totalValueCount++;
  9173. this._current = 0;
  9174. this._lastSecValueCount++;
  9175. };
  9176. /**
  9177. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9178. * @param newCount the count value to add to the monitored count
  9179. * @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.
  9180. */
  9181. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9182. if (!PerfCounter.Enabled) {
  9183. return;
  9184. }
  9185. this._current += newCount;
  9186. if (fetchResult) {
  9187. this._fetchResult();
  9188. }
  9189. };
  9190. /**
  9191. * Start monitoring this performance counter
  9192. */
  9193. PerfCounter.prototype.beginMonitoring = function () {
  9194. if (!PerfCounter.Enabled) {
  9195. return;
  9196. }
  9197. this._startMonitoringTime = Tools.Now;
  9198. };
  9199. /**
  9200. * Compute the time lapsed since the previous beginMonitoring() call.
  9201. * @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
  9202. */
  9203. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9204. if (newFrame === void 0) { newFrame = true; }
  9205. if (!PerfCounter.Enabled) {
  9206. return;
  9207. }
  9208. if (newFrame) {
  9209. this.fetchNewFrame();
  9210. }
  9211. var currentTime = Tools.Now;
  9212. this._current = currentTime - this._startMonitoringTime;
  9213. if (newFrame) {
  9214. this._fetchResult();
  9215. }
  9216. };
  9217. PerfCounter.prototype._fetchResult = function () {
  9218. this._totalAccumulated += this._current;
  9219. this._lastSecAccumulated += this._current;
  9220. // Min/Max update
  9221. this._min = Math.min(this._min, this._current);
  9222. this._max = Math.max(this._max, this._current);
  9223. this._average = this._totalAccumulated / this._totalValueCount;
  9224. // Reset last sec?
  9225. var now = Tools.Now;
  9226. if ((now - this._lastSecTime) > 1000) {
  9227. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9228. this._lastSecTime = now;
  9229. this._lastSecAccumulated = 0;
  9230. this._lastSecValueCount = 0;
  9231. }
  9232. };
  9233. PerfCounter.Enabled = true;
  9234. return PerfCounter;
  9235. }());
  9236. BABYLON.PerfCounter = PerfCounter;
  9237. /**
  9238. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9239. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9240. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9241. * @param name The name of the class, case should be preserved
  9242. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9243. */
  9244. function className(name, module) {
  9245. return function (target) {
  9246. target["__bjsclassName__"] = name;
  9247. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9248. };
  9249. }
  9250. BABYLON.className = className;
  9251. /**
  9252. * An implementation of a loop for asynchronous functions.
  9253. */
  9254. var AsyncLoop = /** @class */ (function () {
  9255. /**
  9256. * Constroctor.
  9257. * @param iterations the number of iterations.
  9258. * @param _fn the function to run each iteration
  9259. * @param _successCallback the callback that will be called upon succesful execution
  9260. * @param offset starting offset.
  9261. */
  9262. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9263. if (offset === void 0) { offset = 0; }
  9264. this.iterations = iterations;
  9265. this._fn = _fn;
  9266. this._successCallback = _successCallback;
  9267. this.index = offset - 1;
  9268. this._done = false;
  9269. }
  9270. /**
  9271. * Execute the next iteration. Must be called after the last iteration was finished.
  9272. */
  9273. AsyncLoop.prototype.executeNext = function () {
  9274. if (!this._done) {
  9275. if (this.index + 1 < this.iterations) {
  9276. ++this.index;
  9277. this._fn(this);
  9278. }
  9279. else {
  9280. this.breakLoop();
  9281. }
  9282. }
  9283. };
  9284. /**
  9285. * Break the loop and run the success callback.
  9286. */
  9287. AsyncLoop.prototype.breakLoop = function () {
  9288. this._done = true;
  9289. this._successCallback();
  9290. };
  9291. /**
  9292. * Helper function
  9293. */
  9294. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9295. if (offset === void 0) { offset = 0; }
  9296. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9297. loop.executeNext();
  9298. return loop;
  9299. };
  9300. /**
  9301. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9302. * @param iterations total number of iterations
  9303. * @param syncedIterations number of synchronous iterations in each async iteration.
  9304. * @param fn the function to call each iteration.
  9305. * @param callback a success call back that will be called when iterating stops.
  9306. * @param breakFunction a break condition (optional)
  9307. * @param timeout timeout settings for the setTimeout function. default - 0.
  9308. * @constructor
  9309. */
  9310. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9311. if (timeout === void 0) { timeout = 0; }
  9312. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9313. if (breakFunction && breakFunction())
  9314. loop.breakLoop();
  9315. else {
  9316. setTimeout(function () {
  9317. for (var i = 0; i < syncedIterations; ++i) {
  9318. var iteration = (loop.index * syncedIterations) + i;
  9319. if (iteration >= iterations)
  9320. break;
  9321. fn(iteration);
  9322. if (breakFunction && breakFunction()) {
  9323. loop.breakLoop();
  9324. break;
  9325. }
  9326. }
  9327. loop.executeNext();
  9328. }, timeout);
  9329. }
  9330. }, callback);
  9331. };
  9332. return AsyncLoop;
  9333. }());
  9334. BABYLON.AsyncLoop = AsyncLoop;
  9335. })(BABYLON || (BABYLON = {}));
  9336. //# sourceMappingURL=babylon.tools.js.map
  9337. var BABYLON;
  9338. (function (BABYLON) {
  9339. var PromiseStates;
  9340. (function (PromiseStates) {
  9341. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9342. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9343. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9344. })(PromiseStates || (PromiseStates = {}));
  9345. var FulFillmentAgregator = /** @class */ (function () {
  9346. function FulFillmentAgregator() {
  9347. this.count = 0;
  9348. this.target = 0;
  9349. this.results = [];
  9350. }
  9351. return FulFillmentAgregator;
  9352. }());
  9353. var InternalPromise = /** @class */ (function () {
  9354. function InternalPromise(resolver) {
  9355. var _this = this;
  9356. this._state = PromiseStates.Pending;
  9357. this._children = new Array();
  9358. this._rejectWasConsumed = false;
  9359. if (!resolver) {
  9360. return;
  9361. }
  9362. try {
  9363. resolver(function (value) {
  9364. _this._resolve(value);
  9365. }, function (reason) {
  9366. _this._reject(reason);
  9367. });
  9368. }
  9369. catch (e) {
  9370. this._reject(e);
  9371. }
  9372. }
  9373. InternalPromise.prototype.catch = function (onRejected) {
  9374. return this.then(undefined, onRejected);
  9375. };
  9376. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9377. var _this = this;
  9378. var newPromise = new InternalPromise();
  9379. newPromise._onFulfilled = onFulfilled;
  9380. newPromise._onRejected = onRejected;
  9381. // Composition
  9382. this._children.push(newPromise);
  9383. if (this._state !== PromiseStates.Pending) {
  9384. BABYLON.Tools.SetImmediate(function () {
  9385. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9386. var returnedValue = newPromise._resolve(_this._result);
  9387. if (returnedValue !== undefined && returnedValue !== null) {
  9388. if (returnedValue._state !== undefined) {
  9389. var returnedPromise = returnedValue;
  9390. newPromise._children.push(returnedPromise);
  9391. newPromise = returnedPromise;
  9392. }
  9393. else {
  9394. newPromise._result = returnedValue;
  9395. }
  9396. }
  9397. }
  9398. else {
  9399. newPromise._reject(_this._reason);
  9400. }
  9401. });
  9402. }
  9403. return newPromise;
  9404. };
  9405. InternalPromise.prototype._moveChildren = function (children) {
  9406. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9407. if (this._state === PromiseStates.Fulfilled) {
  9408. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9409. var child = _b[_i];
  9410. child._resolve(this._result);
  9411. }
  9412. }
  9413. else if (this._state === PromiseStates.Rejected) {
  9414. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9415. var child = _d[_c];
  9416. child._reject(this._reason);
  9417. }
  9418. }
  9419. var _a;
  9420. };
  9421. InternalPromise.prototype._resolve = function (value) {
  9422. try {
  9423. this._state = PromiseStates.Fulfilled;
  9424. this._result = value;
  9425. var returnedValue = null;
  9426. if (this._onFulfilled) {
  9427. returnedValue = this._onFulfilled(value);
  9428. }
  9429. if (returnedValue !== undefined && returnedValue !== null) {
  9430. if (returnedValue._state !== undefined) {
  9431. // Transmit children
  9432. var returnedPromise = returnedValue;
  9433. returnedPromise._moveChildren(this._children);
  9434. }
  9435. else {
  9436. value = returnedValue;
  9437. }
  9438. }
  9439. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9440. var child = _a[_i];
  9441. child._resolve(value);
  9442. }
  9443. this._children.length = 0;
  9444. delete this._onFulfilled;
  9445. delete this._onRejected;
  9446. return returnedValue;
  9447. }
  9448. catch (e) {
  9449. this._reject(e, true);
  9450. }
  9451. return null;
  9452. };
  9453. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9454. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9455. this._state = PromiseStates.Rejected;
  9456. this._reason = reason;
  9457. if (this._onRejected && !onLocalThrow) {
  9458. try {
  9459. this._onRejected(reason);
  9460. this._rejectWasConsumed = true;
  9461. }
  9462. catch (e) {
  9463. reason = e;
  9464. }
  9465. }
  9466. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9467. var child = _a[_i];
  9468. if (this._rejectWasConsumed) {
  9469. child._resolve(null);
  9470. }
  9471. else {
  9472. child._reject(reason);
  9473. }
  9474. }
  9475. this._children.length = 0;
  9476. delete this._onFulfilled;
  9477. delete this._onRejected;
  9478. };
  9479. InternalPromise.resolve = function (value) {
  9480. var newPromise = new InternalPromise();
  9481. newPromise._resolve(value);
  9482. return newPromise;
  9483. };
  9484. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9485. promise.then(function (value) {
  9486. agregator.results[index] = value;
  9487. agregator.count++;
  9488. if (agregator.count === agregator.target) {
  9489. agregator.rootPromise._resolve(agregator.results);
  9490. }
  9491. return null;
  9492. }, function (reason) {
  9493. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9494. agregator.rootPromise._reject(reason);
  9495. }
  9496. });
  9497. };
  9498. InternalPromise.all = function (promises) {
  9499. var newPromise = new InternalPromise();
  9500. var agregator = new FulFillmentAgregator();
  9501. agregator.target = promises.length;
  9502. agregator.rootPromise = newPromise;
  9503. if (promises.length) {
  9504. for (var index = 0; index < promises.length; index++) {
  9505. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9506. }
  9507. }
  9508. else {
  9509. newPromise._resolve([]);
  9510. }
  9511. return newPromise;
  9512. };
  9513. InternalPromise.race = function (promises) {
  9514. var newPromise = new InternalPromise();
  9515. if (promises.length) {
  9516. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9517. var promise = promises_1[_i];
  9518. promise.then(function (value) {
  9519. if (newPromise) {
  9520. newPromise._resolve(value);
  9521. newPromise = null;
  9522. }
  9523. return null;
  9524. }, function (reason) {
  9525. if (newPromise) {
  9526. newPromise._reject(reason);
  9527. newPromise = null;
  9528. }
  9529. });
  9530. }
  9531. }
  9532. return newPromise;
  9533. };
  9534. return InternalPromise;
  9535. }());
  9536. /**
  9537. * Helper class that provides a small promise polyfill
  9538. */
  9539. var PromisePolyfill = /** @class */ (function () {
  9540. function PromisePolyfill() {
  9541. }
  9542. /**
  9543. * Static function used to check if the polyfill is required
  9544. * If this is the case then the function will inject the polyfill to window.Promise
  9545. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9546. */
  9547. PromisePolyfill.Apply = function (force) {
  9548. if (force === void 0) { force = false; }
  9549. if (force || typeof Promise === 'undefined') {
  9550. var root = window;
  9551. root.Promise = InternalPromise;
  9552. }
  9553. };
  9554. return PromisePolyfill;
  9555. }());
  9556. BABYLON.PromisePolyfill = PromisePolyfill;
  9557. })(BABYLON || (BABYLON = {}));
  9558. //# sourceMappingURL=babylon.promise.js.map
  9559. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9560. var BABYLON;
  9561. (function (BABYLON) {
  9562. /**
  9563. * Helper class to push actions to a pool of workers.
  9564. */
  9565. var WorkerPool = /** @class */ (function () {
  9566. /**
  9567. * Constructor
  9568. * @param workers Array of workers to use for actions
  9569. */
  9570. function WorkerPool(workers) {
  9571. this._pendingActions = new Array();
  9572. this._workerInfos = workers.map(function (worker) { return ({
  9573. worker: worker,
  9574. active: false
  9575. }); });
  9576. }
  9577. /**
  9578. * Terminates all workers and clears any pending actions.
  9579. */
  9580. WorkerPool.prototype.dispose = function () {
  9581. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9582. var workerInfo = _a[_i];
  9583. workerInfo.worker.terminate();
  9584. }
  9585. delete this._workerInfos;
  9586. delete this._pendingActions;
  9587. };
  9588. /**
  9589. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9590. * pended until a worker has completed its action.
  9591. * @param action The action to perform. Call onComplete when the action is complete.
  9592. */
  9593. WorkerPool.prototype.push = function (action) {
  9594. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9595. var workerInfo = _a[_i];
  9596. if (!workerInfo.active) {
  9597. this._execute(workerInfo, action);
  9598. return;
  9599. }
  9600. }
  9601. this._pendingActions.push(action);
  9602. };
  9603. WorkerPool.prototype._execute = function (workerInfo, action) {
  9604. var _this = this;
  9605. workerInfo.active = true;
  9606. action(workerInfo.worker, function () {
  9607. workerInfo.active = false;
  9608. var nextAction = _this._pendingActions.shift();
  9609. if (nextAction) {
  9610. _this._execute(workerInfo, nextAction);
  9611. }
  9612. });
  9613. };
  9614. return WorkerPool;
  9615. }());
  9616. BABYLON.WorkerPool = WorkerPool;
  9617. })(BABYLON || (BABYLON = {}));
  9618. //# sourceMappingURL=babylon.workerPool.js.map
  9619. var BABYLON;
  9620. (function (BABYLON) {
  9621. var _AlphaState = /** @class */ (function () {
  9622. /**
  9623. * Initializes the state.
  9624. */
  9625. function _AlphaState() {
  9626. this._isAlphaBlendDirty = false;
  9627. this._isBlendFunctionParametersDirty = false;
  9628. this._isBlendEquationParametersDirty = false;
  9629. this._isBlendConstantsDirty = false;
  9630. this._alphaBlend = false;
  9631. this._blendFunctionParameters = new Array(4);
  9632. this._blendEquationParameters = new Array(2);
  9633. this._blendConstants = new Array(4);
  9634. this.reset();
  9635. }
  9636. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9637. get: function () {
  9638. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9639. },
  9640. enumerable: true,
  9641. configurable: true
  9642. });
  9643. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9644. get: function () {
  9645. return this._alphaBlend;
  9646. },
  9647. set: function (value) {
  9648. if (this._alphaBlend === value) {
  9649. return;
  9650. }
  9651. this._alphaBlend = value;
  9652. this._isAlphaBlendDirty = true;
  9653. },
  9654. enumerable: true,
  9655. configurable: true
  9656. });
  9657. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9658. if (this._blendConstants[0] === r &&
  9659. this._blendConstants[1] === g &&
  9660. this._blendConstants[2] === b &&
  9661. this._blendConstants[3] === a) {
  9662. return;
  9663. }
  9664. this._blendConstants[0] = r;
  9665. this._blendConstants[1] = g;
  9666. this._blendConstants[2] = b;
  9667. this._blendConstants[3] = a;
  9668. this._isBlendConstantsDirty = true;
  9669. };
  9670. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9671. if (this._blendFunctionParameters[0] === value0 &&
  9672. this._blendFunctionParameters[1] === value1 &&
  9673. this._blendFunctionParameters[2] === value2 &&
  9674. this._blendFunctionParameters[3] === value3) {
  9675. return;
  9676. }
  9677. this._blendFunctionParameters[0] = value0;
  9678. this._blendFunctionParameters[1] = value1;
  9679. this._blendFunctionParameters[2] = value2;
  9680. this._blendFunctionParameters[3] = value3;
  9681. this._isBlendFunctionParametersDirty = true;
  9682. };
  9683. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9684. if (this._blendEquationParameters[0] === rgb &&
  9685. this._blendEquationParameters[1] === alpha) {
  9686. return;
  9687. }
  9688. this._blendEquationParameters[0] = rgb;
  9689. this._blendEquationParameters[1] = alpha;
  9690. this._isBlendEquationParametersDirty = true;
  9691. };
  9692. _AlphaState.prototype.reset = function () {
  9693. this._alphaBlend = false;
  9694. this._blendFunctionParameters[0] = null;
  9695. this._blendFunctionParameters[1] = null;
  9696. this._blendFunctionParameters[2] = null;
  9697. this._blendFunctionParameters[3] = null;
  9698. this._blendEquationParameters[0] = null;
  9699. this._blendEquationParameters[1] = null;
  9700. this._blendConstants[0] = null;
  9701. this._blendConstants[1] = null;
  9702. this._blendConstants[2] = null;
  9703. this._blendConstants[3] = null;
  9704. this._isAlphaBlendDirty = true;
  9705. this._isBlendFunctionParametersDirty = false;
  9706. this._isBlendEquationParametersDirty = false;
  9707. this._isBlendConstantsDirty = false;
  9708. };
  9709. _AlphaState.prototype.apply = function (gl) {
  9710. if (!this.isDirty) {
  9711. return;
  9712. }
  9713. // Alpha blend
  9714. if (this._isAlphaBlendDirty) {
  9715. if (this._alphaBlend) {
  9716. gl.enable(gl.BLEND);
  9717. }
  9718. else {
  9719. gl.disable(gl.BLEND);
  9720. }
  9721. this._isAlphaBlendDirty = false;
  9722. }
  9723. // Alpha function
  9724. if (this._isBlendFunctionParametersDirty) {
  9725. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9726. this._isBlendFunctionParametersDirty = false;
  9727. }
  9728. // Alpha equation
  9729. if (this._isBlendEquationParametersDirty) {
  9730. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9731. this._isBlendEquationParametersDirty = false;
  9732. }
  9733. // Constants
  9734. if (this._isBlendConstantsDirty) {
  9735. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9736. this._isBlendConstantsDirty = false;
  9737. }
  9738. };
  9739. return _AlphaState;
  9740. }());
  9741. BABYLON._AlphaState = _AlphaState;
  9742. })(BABYLON || (BABYLON = {}));
  9743. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9744. var BABYLON;
  9745. (function (BABYLON) {
  9746. var _DepthCullingState = /** @class */ (function () {
  9747. /**
  9748. * Initializes the state.
  9749. */
  9750. function _DepthCullingState() {
  9751. this._isDepthTestDirty = false;
  9752. this._isDepthMaskDirty = false;
  9753. this._isDepthFuncDirty = false;
  9754. this._isCullFaceDirty = false;
  9755. this._isCullDirty = false;
  9756. this._isZOffsetDirty = false;
  9757. this._isFrontFaceDirty = false;
  9758. this.reset();
  9759. }
  9760. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9761. get: function () {
  9762. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9763. },
  9764. enumerable: true,
  9765. configurable: true
  9766. });
  9767. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9768. get: function () {
  9769. return this._zOffset;
  9770. },
  9771. set: function (value) {
  9772. if (this._zOffset === value) {
  9773. return;
  9774. }
  9775. this._zOffset = value;
  9776. this._isZOffsetDirty = true;
  9777. },
  9778. enumerable: true,
  9779. configurable: true
  9780. });
  9781. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9782. get: function () {
  9783. return this._cullFace;
  9784. },
  9785. set: function (value) {
  9786. if (this._cullFace === value) {
  9787. return;
  9788. }
  9789. this._cullFace = value;
  9790. this._isCullFaceDirty = true;
  9791. },
  9792. enumerable: true,
  9793. configurable: true
  9794. });
  9795. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9796. get: function () {
  9797. return this._cull;
  9798. },
  9799. set: function (value) {
  9800. if (this._cull === value) {
  9801. return;
  9802. }
  9803. this._cull = value;
  9804. this._isCullDirty = true;
  9805. },
  9806. enumerable: true,
  9807. configurable: true
  9808. });
  9809. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9810. get: function () {
  9811. return this._depthFunc;
  9812. },
  9813. set: function (value) {
  9814. if (this._depthFunc === value) {
  9815. return;
  9816. }
  9817. this._depthFunc = value;
  9818. this._isDepthFuncDirty = true;
  9819. },
  9820. enumerable: true,
  9821. configurable: true
  9822. });
  9823. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9824. get: function () {
  9825. return this._depthMask;
  9826. },
  9827. set: function (value) {
  9828. if (this._depthMask === value) {
  9829. return;
  9830. }
  9831. this._depthMask = value;
  9832. this._isDepthMaskDirty = true;
  9833. },
  9834. enumerable: true,
  9835. configurable: true
  9836. });
  9837. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9838. get: function () {
  9839. return this._depthTest;
  9840. },
  9841. set: function (value) {
  9842. if (this._depthTest === value) {
  9843. return;
  9844. }
  9845. this._depthTest = value;
  9846. this._isDepthTestDirty = true;
  9847. },
  9848. enumerable: true,
  9849. configurable: true
  9850. });
  9851. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9852. get: function () {
  9853. return this._frontFace;
  9854. },
  9855. set: function (value) {
  9856. if (this._frontFace === value) {
  9857. return;
  9858. }
  9859. this._frontFace = value;
  9860. this._isFrontFaceDirty = true;
  9861. },
  9862. enumerable: true,
  9863. configurable: true
  9864. });
  9865. _DepthCullingState.prototype.reset = function () {
  9866. this._depthMask = true;
  9867. this._depthTest = true;
  9868. this._depthFunc = null;
  9869. this._cullFace = null;
  9870. this._cull = null;
  9871. this._zOffset = 0;
  9872. this._frontFace = null;
  9873. this._isDepthTestDirty = true;
  9874. this._isDepthMaskDirty = true;
  9875. this._isDepthFuncDirty = false;
  9876. this._isCullFaceDirty = false;
  9877. this._isCullDirty = false;
  9878. this._isZOffsetDirty = false;
  9879. this._isFrontFaceDirty = false;
  9880. };
  9881. _DepthCullingState.prototype.apply = function (gl) {
  9882. if (!this.isDirty) {
  9883. return;
  9884. }
  9885. // Cull
  9886. if (this._isCullDirty) {
  9887. if (this.cull) {
  9888. gl.enable(gl.CULL_FACE);
  9889. }
  9890. else {
  9891. gl.disable(gl.CULL_FACE);
  9892. }
  9893. this._isCullDirty = false;
  9894. }
  9895. // Cull face
  9896. if (this._isCullFaceDirty) {
  9897. gl.cullFace(this.cullFace);
  9898. this._isCullFaceDirty = false;
  9899. }
  9900. // Depth mask
  9901. if (this._isDepthMaskDirty) {
  9902. gl.depthMask(this.depthMask);
  9903. this._isDepthMaskDirty = false;
  9904. }
  9905. // Depth test
  9906. if (this._isDepthTestDirty) {
  9907. if (this.depthTest) {
  9908. gl.enable(gl.DEPTH_TEST);
  9909. }
  9910. else {
  9911. gl.disable(gl.DEPTH_TEST);
  9912. }
  9913. this._isDepthTestDirty = false;
  9914. }
  9915. // Depth func
  9916. if (this._isDepthFuncDirty) {
  9917. gl.depthFunc(this.depthFunc);
  9918. this._isDepthFuncDirty = false;
  9919. }
  9920. // zOffset
  9921. if (this._isZOffsetDirty) {
  9922. if (this.zOffset) {
  9923. gl.enable(gl.POLYGON_OFFSET_FILL);
  9924. gl.polygonOffset(this.zOffset, 0);
  9925. }
  9926. else {
  9927. gl.disable(gl.POLYGON_OFFSET_FILL);
  9928. }
  9929. this._isZOffsetDirty = false;
  9930. }
  9931. // Front face
  9932. if (this._isFrontFaceDirty) {
  9933. gl.frontFace(this.frontFace);
  9934. this._isFrontFaceDirty = false;
  9935. }
  9936. };
  9937. return _DepthCullingState;
  9938. }());
  9939. BABYLON._DepthCullingState = _DepthCullingState;
  9940. })(BABYLON || (BABYLON = {}));
  9941. //# sourceMappingURL=babylon.depthCullingState.js.map
  9942. var BABYLON;
  9943. (function (BABYLON) {
  9944. var _StencilState = /** @class */ (function () {
  9945. function _StencilState() {
  9946. this._isStencilTestDirty = false;
  9947. this._isStencilMaskDirty = false;
  9948. this._isStencilFuncDirty = false;
  9949. this._isStencilOpDirty = false;
  9950. this.reset();
  9951. }
  9952. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9953. get: function () {
  9954. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9955. },
  9956. enumerable: true,
  9957. configurable: true
  9958. });
  9959. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9960. get: function () {
  9961. return this._stencilFunc;
  9962. },
  9963. set: function (value) {
  9964. if (this._stencilFunc === value) {
  9965. return;
  9966. }
  9967. this._stencilFunc = value;
  9968. this._isStencilFuncDirty = true;
  9969. },
  9970. enumerable: true,
  9971. configurable: true
  9972. });
  9973. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9974. get: function () {
  9975. return this._stencilFuncRef;
  9976. },
  9977. set: function (value) {
  9978. if (this._stencilFuncRef === value) {
  9979. return;
  9980. }
  9981. this._stencilFuncRef = value;
  9982. this._isStencilFuncDirty = true;
  9983. },
  9984. enumerable: true,
  9985. configurable: true
  9986. });
  9987. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9988. get: function () {
  9989. return this._stencilFuncMask;
  9990. },
  9991. set: function (value) {
  9992. if (this._stencilFuncMask === value) {
  9993. return;
  9994. }
  9995. this._stencilFuncMask = value;
  9996. this._isStencilFuncDirty = true;
  9997. },
  9998. enumerable: true,
  9999. configurable: true
  10000. });
  10001. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10002. get: function () {
  10003. return this._stencilOpStencilFail;
  10004. },
  10005. set: function (value) {
  10006. if (this._stencilOpStencilFail === value) {
  10007. return;
  10008. }
  10009. this._stencilOpStencilFail = value;
  10010. this._isStencilOpDirty = true;
  10011. },
  10012. enumerable: true,
  10013. configurable: true
  10014. });
  10015. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10016. get: function () {
  10017. return this._stencilOpDepthFail;
  10018. },
  10019. set: function (value) {
  10020. if (this._stencilOpDepthFail === value) {
  10021. return;
  10022. }
  10023. this._stencilOpDepthFail = value;
  10024. this._isStencilOpDirty = true;
  10025. },
  10026. enumerable: true,
  10027. configurable: true
  10028. });
  10029. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10030. get: function () {
  10031. return this._stencilOpStencilDepthPass;
  10032. },
  10033. set: function (value) {
  10034. if (this._stencilOpStencilDepthPass === value) {
  10035. return;
  10036. }
  10037. this._stencilOpStencilDepthPass = value;
  10038. this._isStencilOpDirty = true;
  10039. },
  10040. enumerable: true,
  10041. configurable: true
  10042. });
  10043. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10044. get: function () {
  10045. return this._stencilMask;
  10046. },
  10047. set: function (value) {
  10048. if (this._stencilMask === value) {
  10049. return;
  10050. }
  10051. this._stencilMask = value;
  10052. this._isStencilMaskDirty = true;
  10053. },
  10054. enumerable: true,
  10055. configurable: true
  10056. });
  10057. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10058. get: function () {
  10059. return this._stencilTest;
  10060. },
  10061. set: function (value) {
  10062. if (this._stencilTest === value) {
  10063. return;
  10064. }
  10065. this._stencilTest = value;
  10066. this._isStencilTestDirty = true;
  10067. },
  10068. enumerable: true,
  10069. configurable: true
  10070. });
  10071. _StencilState.prototype.reset = function () {
  10072. this._stencilTest = false;
  10073. this._stencilMask = 0xFF;
  10074. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10075. this._stencilFuncRef = 1;
  10076. this._stencilFuncMask = 0xFF;
  10077. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10078. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10079. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10080. this._isStencilTestDirty = true;
  10081. this._isStencilMaskDirty = true;
  10082. this._isStencilFuncDirty = true;
  10083. this._isStencilOpDirty = true;
  10084. };
  10085. _StencilState.prototype.apply = function (gl) {
  10086. if (!this.isDirty) {
  10087. return;
  10088. }
  10089. // Stencil test
  10090. if (this._isStencilTestDirty) {
  10091. if (this.stencilTest) {
  10092. gl.enable(gl.STENCIL_TEST);
  10093. }
  10094. else {
  10095. gl.disable(gl.STENCIL_TEST);
  10096. }
  10097. this._isStencilTestDirty = false;
  10098. }
  10099. // Stencil mask
  10100. if (this._isStencilMaskDirty) {
  10101. gl.stencilMask(this.stencilMask);
  10102. this._isStencilMaskDirty = false;
  10103. }
  10104. // Stencil func
  10105. if (this._isStencilFuncDirty) {
  10106. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10107. this._isStencilFuncDirty = false;
  10108. }
  10109. // Stencil op
  10110. if (this._isStencilOpDirty) {
  10111. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10112. this._isStencilOpDirty = false;
  10113. }
  10114. };
  10115. return _StencilState;
  10116. }());
  10117. BABYLON._StencilState = _StencilState;
  10118. })(BABYLON || (BABYLON = {}));
  10119. //# sourceMappingURL=babylon.stencilState.js.map
  10120. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10121. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10122. s = arguments[i];
  10123. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10124. t[p] = s[p];
  10125. }
  10126. return t;
  10127. };
  10128. var BABYLON;
  10129. (function (BABYLON) {
  10130. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10131. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10132. };
  10133. var compileRawShader = function (gl, source, type) {
  10134. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10135. gl.shaderSource(shader, source);
  10136. gl.compileShader(shader);
  10137. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10138. var log = gl.getShaderInfoLog(shader);
  10139. if (log) {
  10140. throw new Error(log);
  10141. }
  10142. }
  10143. if (!shader) {
  10144. throw new Error("Something went wrong while compile the shader.");
  10145. }
  10146. return shader;
  10147. };
  10148. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10149. var magFilter = gl.NEAREST;
  10150. var minFilter = gl.NEAREST;
  10151. switch (samplingMode) {
  10152. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10153. magFilter = gl.LINEAR;
  10154. if (generateMipMaps) {
  10155. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10156. }
  10157. else {
  10158. minFilter = gl.LINEAR;
  10159. }
  10160. break;
  10161. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10162. magFilter = gl.LINEAR;
  10163. if (generateMipMaps) {
  10164. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10165. }
  10166. else {
  10167. minFilter = gl.LINEAR;
  10168. }
  10169. break;
  10170. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10171. magFilter = gl.NEAREST;
  10172. if (generateMipMaps) {
  10173. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10174. }
  10175. else {
  10176. minFilter = gl.NEAREST;
  10177. }
  10178. break;
  10179. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10180. magFilter = gl.NEAREST;
  10181. if (generateMipMaps) {
  10182. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10183. }
  10184. else {
  10185. minFilter = gl.NEAREST;
  10186. }
  10187. break;
  10188. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10189. magFilter = gl.NEAREST;
  10190. if (generateMipMaps) {
  10191. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10192. }
  10193. else {
  10194. minFilter = gl.LINEAR;
  10195. }
  10196. break;
  10197. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10198. magFilter = gl.NEAREST;
  10199. if (generateMipMaps) {
  10200. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10201. }
  10202. else {
  10203. minFilter = gl.LINEAR;
  10204. }
  10205. break;
  10206. case BABYLON.Texture.NEAREST_LINEAR:
  10207. magFilter = gl.NEAREST;
  10208. minFilter = gl.LINEAR;
  10209. break;
  10210. case BABYLON.Texture.NEAREST_NEAREST:
  10211. magFilter = gl.NEAREST;
  10212. minFilter = gl.NEAREST;
  10213. break;
  10214. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10215. magFilter = gl.LINEAR;
  10216. if (generateMipMaps) {
  10217. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10218. }
  10219. else {
  10220. minFilter = gl.NEAREST;
  10221. }
  10222. break;
  10223. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10224. magFilter = gl.LINEAR;
  10225. if (generateMipMaps) {
  10226. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10227. }
  10228. else {
  10229. minFilter = gl.NEAREST;
  10230. }
  10231. break;
  10232. case BABYLON.Texture.LINEAR_LINEAR:
  10233. magFilter = gl.LINEAR;
  10234. minFilter = gl.LINEAR;
  10235. break;
  10236. case BABYLON.Texture.LINEAR_NEAREST:
  10237. magFilter = gl.LINEAR;
  10238. minFilter = gl.NEAREST;
  10239. break;
  10240. }
  10241. return {
  10242. min: minFilter,
  10243. mag: magFilter
  10244. };
  10245. };
  10246. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10247. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10248. var img;
  10249. var onload = function () {
  10250. loadedImages[index] = img;
  10251. loadedImages._internalCount++;
  10252. if (scene) {
  10253. scene._removePendingData(img);
  10254. }
  10255. if (loadedImages._internalCount === 6) {
  10256. onfinish(loadedImages);
  10257. }
  10258. };
  10259. var onerror = function (message, exception) {
  10260. if (scene) {
  10261. scene._removePendingData(img);
  10262. }
  10263. if (onErrorCallBack) {
  10264. onErrorCallBack(message, exception);
  10265. }
  10266. };
  10267. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10268. if (scene) {
  10269. scene._addPendingData(img);
  10270. }
  10271. };
  10272. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10273. if (onError === void 0) { onError = null; }
  10274. var loadedImages = [];
  10275. loadedImages._internalCount = 0;
  10276. for (var index = 0; index < 6; index++) {
  10277. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10278. }
  10279. };
  10280. var BufferPointer = /** @class */ (function () {
  10281. function BufferPointer() {
  10282. }
  10283. return BufferPointer;
  10284. }());
  10285. var InstancingAttributeInfo = /** @class */ (function () {
  10286. function InstancingAttributeInfo() {
  10287. }
  10288. return InstancingAttributeInfo;
  10289. }());
  10290. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10291. /**
  10292. * Define options used to create a render target texture
  10293. */
  10294. var RenderTargetCreationOptions = /** @class */ (function () {
  10295. function RenderTargetCreationOptions() {
  10296. }
  10297. return RenderTargetCreationOptions;
  10298. }());
  10299. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10300. /**
  10301. * Define options used to create a depth texture
  10302. */
  10303. var DepthTextureCreationOptions = /** @class */ (function () {
  10304. function DepthTextureCreationOptions() {
  10305. }
  10306. return DepthTextureCreationOptions;
  10307. }());
  10308. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10309. /**
  10310. * Regroup several parameters relative to the browser in use
  10311. */
  10312. var EngineCapabilities = /** @class */ (function () {
  10313. function EngineCapabilities() {
  10314. }
  10315. return EngineCapabilities;
  10316. }());
  10317. BABYLON.EngineCapabilities = EngineCapabilities;
  10318. /**
  10319. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10320. */
  10321. var Engine = /** @class */ (function () {
  10322. /**
  10323. * @constructor
  10324. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10325. * @param antialias defines enable antialiasing (default: false)
  10326. * @param options defines further options to be sent to the getContext() function
  10327. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10328. */
  10329. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10330. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10331. var _this = this;
  10332. // Public members
  10333. this.forcePOTTextures = false;
  10334. this.isFullscreen = false;
  10335. this.isPointerLock = false;
  10336. this.cullBackFaces = true;
  10337. this.renderEvenInBackground = true;
  10338. this.preventCacheWipeBetweenFrames = false;
  10339. // To enable/disable IDB support and avoid XHR on .manifest
  10340. this.enableOfflineSupport = false;
  10341. this.scenes = new Array();
  10342. this.postProcesses = new Array();
  10343. // Observables
  10344. /**
  10345. * Observable event triggered each time the rendering canvas is resized
  10346. */
  10347. this.onResizeObservable = new BABYLON.Observable();
  10348. /**
  10349. * Observable event triggered each time the canvas loses focus
  10350. */
  10351. this.onCanvasBlurObservable = new BABYLON.Observable();
  10352. /**
  10353. * Observable event triggered each time the canvas gains focus
  10354. */
  10355. this.onCanvasFocusObservable = new BABYLON.Observable();
  10356. /**
  10357. * Observable event triggered each time the canvas receives pointerout event
  10358. */
  10359. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10360. /**
  10361. * Observable event triggered before each texture is initialized
  10362. */
  10363. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10364. //WebVR
  10365. this._vrDisplay = undefined;
  10366. this._vrSupported = false;
  10367. this._vrExclusivePointerMode = false;
  10368. // Uniform buffers list
  10369. this.disableUniformBuffers = false;
  10370. this._uniformBuffers = new Array();
  10371. // Observables
  10372. /**
  10373. * Observable raised when the engine begins a new frame
  10374. */
  10375. this.onBeginFrameObservable = new BABYLON.Observable();
  10376. /**
  10377. * Observable raised when the engine ends the current frame
  10378. */
  10379. this.onEndFrameObservable = new BABYLON.Observable();
  10380. /**
  10381. * Observable raised when the engine is about to compile a shader
  10382. */
  10383. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10384. /**
  10385. * Observable raised when the engine has jsut compiled a shader
  10386. */
  10387. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10388. this._windowIsBackground = false;
  10389. this._webGLVersion = 1.0;
  10390. this._badOS = false;
  10391. this._badDesktopOS = false;
  10392. /**
  10393. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10394. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10395. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10396. */
  10397. this.disableTextureBindingOptimization = false;
  10398. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10399. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10400. this.onVRRequestPresentStart = new BABYLON.Observable();
  10401. this._colorWrite = true;
  10402. this._drawCalls = new BABYLON.PerfCounter();
  10403. this._textureCollisions = new BABYLON.PerfCounter();
  10404. this._renderingQueueLaunched = false;
  10405. this._activeRenderLoops = new Array();
  10406. // Deterministic lockstepMaxSteps
  10407. this._deterministicLockstep = false;
  10408. this._lockstepMaxSteps = 4;
  10409. // Lost context
  10410. this.onContextLostObservable = new BABYLON.Observable();
  10411. this.onContextRestoredObservable = new BABYLON.Observable();
  10412. this._contextWasLost = false;
  10413. this._doNotHandleContextLost = false;
  10414. // FPS
  10415. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10416. this._fps = 60;
  10417. this._deltaTime = 0;
  10418. /**
  10419. * Turn this value on if you want to pause FPS computation when in background
  10420. */
  10421. this.disablePerformanceMonitorInBackground = false;
  10422. // States
  10423. this._depthCullingState = new BABYLON._DepthCullingState();
  10424. this._stencilState = new BABYLON._StencilState();
  10425. this._alphaState = new BABYLON._AlphaState();
  10426. this._alphaMode = Engine.ALPHA_DISABLE;
  10427. // Cache
  10428. this._internalTexturesCache = new Array();
  10429. this._activeChannel = 0;
  10430. this._currentTextureChannel = -1;
  10431. this._boundTexturesCache = {};
  10432. this._compiledEffects = {};
  10433. this._vertexAttribArraysEnabled = [];
  10434. this._uintIndicesCurrentlySet = false;
  10435. this._currentBoundBuffer = new Array();
  10436. this._currentBufferPointers = new Array();
  10437. this._currentInstanceLocations = new Array();
  10438. this._currentInstanceBuffers = new Array();
  10439. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10440. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10441. this._vaoRecordInProgress = false;
  10442. this._mustWipeVertexAttributes = false;
  10443. this._nextFreeTextureSlots = new Array();
  10444. this._maxSimultaneousTextures = 0;
  10445. this._activeRequests = new Array();
  10446. // Hardware supported Compressed Textures
  10447. this._texturesSupported = new Array();
  10448. this._onVRFullScreenTriggered = function () {
  10449. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10450. //get the old size before we change
  10451. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10452. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10453. //get the width and height, change the render size
  10454. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10455. _this.setHardwareScalingLevel(1);
  10456. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10457. }
  10458. else {
  10459. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10460. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10461. }
  10462. };
  10463. this._boundUniforms = {};
  10464. // Register promises
  10465. BABYLON.PromisePolyfill.Apply();
  10466. var canvas = null;
  10467. Engine.Instances.push(this);
  10468. if (!canvasOrContext) {
  10469. return;
  10470. }
  10471. options = options || {};
  10472. if (canvasOrContext.getContext) {
  10473. canvas = canvasOrContext;
  10474. this._renderingCanvas = canvas;
  10475. if (antialias != null) {
  10476. options.antialias = antialias;
  10477. }
  10478. if (options.deterministicLockstep === undefined) {
  10479. options.deterministicLockstep = false;
  10480. }
  10481. if (options.lockstepMaxSteps === undefined) {
  10482. options.lockstepMaxSteps = 4;
  10483. }
  10484. if (options.preserveDrawingBuffer === undefined) {
  10485. options.preserveDrawingBuffer = false;
  10486. }
  10487. if (options.audioEngine === undefined) {
  10488. options.audioEngine = true;
  10489. }
  10490. if (options.stencil === undefined) {
  10491. options.stencil = true;
  10492. }
  10493. this._deterministicLockstep = options.deterministicLockstep;
  10494. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10495. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10496. // Exceptions
  10497. if (navigator && navigator.userAgent) {
  10498. var ua = navigator.userAgent;
  10499. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10500. var exception = _a[_i];
  10501. var key = exception.key;
  10502. var targets = exception.targets;
  10503. if (ua.indexOf(key) > -1) {
  10504. if (exception.capture && exception.captureConstraint) {
  10505. var capture = exception.capture;
  10506. var constraint = exception.captureConstraint;
  10507. var regex = new RegExp(capture);
  10508. var matches = regex.exec(ua);
  10509. if (matches && matches.length > 0) {
  10510. var capturedValue = parseInt(matches[matches.length - 1]);
  10511. if (capturedValue >= constraint) {
  10512. continue;
  10513. }
  10514. }
  10515. }
  10516. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10517. var target = targets_1[_b];
  10518. switch (target) {
  10519. case "uniformBuffer":
  10520. this.disableUniformBuffers = true;
  10521. break;
  10522. case "textureBindingOptimization":
  10523. this.disableTextureBindingOptimization = true;
  10524. break;
  10525. }
  10526. }
  10527. }
  10528. }
  10529. }
  10530. // GL
  10531. if (!options.disableWebGL2Support) {
  10532. try {
  10533. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10534. if (this._gl) {
  10535. this._webGLVersion = 2.0;
  10536. }
  10537. }
  10538. catch (e) {
  10539. // Do nothing
  10540. }
  10541. }
  10542. if (!this._gl) {
  10543. if (!canvas) {
  10544. throw new Error("The provided canvas is null or undefined.");
  10545. }
  10546. try {
  10547. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10548. }
  10549. catch (e) {
  10550. throw new Error("WebGL not supported");
  10551. }
  10552. }
  10553. if (!this._gl) {
  10554. throw new Error("WebGL not supported");
  10555. }
  10556. this._onCanvasFocus = function () {
  10557. _this.onCanvasFocusObservable.notifyObservers(_this);
  10558. };
  10559. this._onCanvasBlur = function () {
  10560. _this.onCanvasBlurObservable.notifyObservers(_this);
  10561. };
  10562. canvas.addEventListener("focus", this._onCanvasFocus);
  10563. canvas.addEventListener("blur", this._onCanvasBlur);
  10564. this._onBlur = function () {
  10565. if (_this.disablePerformanceMonitorInBackground) {
  10566. _this._performanceMonitor.disable();
  10567. }
  10568. _this._windowIsBackground = true;
  10569. };
  10570. this._onFocus = function () {
  10571. if (_this.disablePerformanceMonitorInBackground) {
  10572. _this._performanceMonitor.enable();
  10573. }
  10574. _this._windowIsBackground = false;
  10575. };
  10576. this._onCanvasPointerOut = function (ev) {
  10577. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10578. };
  10579. window.addEventListener("blur", this._onBlur);
  10580. window.addEventListener("focus", this._onFocus);
  10581. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10582. // Context lost
  10583. if (!this._doNotHandleContextLost) {
  10584. this._onContextLost = function (evt) {
  10585. evt.preventDefault();
  10586. _this._contextWasLost = true;
  10587. BABYLON.Tools.Warn("WebGL context lost.");
  10588. _this.onContextLostObservable.notifyObservers(_this);
  10589. };
  10590. this._onContextRestored = function (evt) {
  10591. // Adding a timeout to avoid race condition at browser level
  10592. setTimeout(function () {
  10593. // Rebuild gl context
  10594. _this._initGLContext();
  10595. // Rebuild effects
  10596. _this._rebuildEffects();
  10597. // Rebuild textures
  10598. _this._rebuildInternalTextures();
  10599. // Rebuild buffers
  10600. _this._rebuildBuffers();
  10601. // Cache
  10602. _this.wipeCaches(true);
  10603. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10604. _this.onContextRestoredObservable.notifyObservers(_this);
  10605. _this._contextWasLost = false;
  10606. }, 0);
  10607. };
  10608. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10609. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10610. }
  10611. }
  10612. else {
  10613. this._gl = canvasOrContext;
  10614. this._renderingCanvas = this._gl.canvas;
  10615. if (this._gl.renderbufferStorageMultisample) {
  10616. this._webGLVersion = 2.0;
  10617. }
  10618. options.stencil = this._gl.getContextAttributes().stencil;
  10619. }
  10620. // Viewport
  10621. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10622. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10623. this.resize();
  10624. this._isStencilEnable = options.stencil ? true : false;
  10625. this._initGLContext();
  10626. if (canvas) {
  10627. // Fullscreen
  10628. this._onFullscreenChange = function () {
  10629. if (document.fullscreen !== undefined) {
  10630. _this.isFullscreen = document.fullscreen;
  10631. }
  10632. else if (document.mozFullScreen !== undefined) {
  10633. _this.isFullscreen = document.mozFullScreen;
  10634. }
  10635. else if (document.webkitIsFullScreen !== undefined) {
  10636. _this.isFullscreen = document.webkitIsFullScreen;
  10637. }
  10638. else if (document.msIsFullScreen !== undefined) {
  10639. _this.isFullscreen = document.msIsFullScreen;
  10640. }
  10641. // Pointer lock
  10642. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10643. canvas.requestPointerLock = canvas.requestPointerLock ||
  10644. canvas.msRequestPointerLock ||
  10645. canvas.mozRequestPointerLock ||
  10646. canvas.webkitRequestPointerLock;
  10647. if (canvas.requestPointerLock) {
  10648. canvas.requestPointerLock();
  10649. }
  10650. }
  10651. };
  10652. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10653. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10654. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10655. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10656. // Pointer lock
  10657. this._onPointerLockChange = function () {
  10658. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10659. document.webkitPointerLockElement === canvas ||
  10660. document.msPointerLockElement === canvas ||
  10661. document.pointerLockElement === canvas);
  10662. };
  10663. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10664. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10665. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10666. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10667. this._onVRDisplayPointerRestricted = function () {
  10668. if (canvas) {
  10669. canvas.requestPointerLock();
  10670. }
  10671. };
  10672. this._onVRDisplayPointerUnrestricted = function () {
  10673. document.exitPointerLock();
  10674. };
  10675. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10676. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10677. }
  10678. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10679. Engine.audioEngine = new BABYLON.AudioEngine();
  10680. }
  10681. // Prepare buffer pointers
  10682. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10683. this._currentBufferPointers[i] = new BufferPointer();
  10684. }
  10685. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10686. // Load WebVR Devices
  10687. if (options.autoEnableWebVR) {
  10688. this.initWebVR();
  10689. }
  10690. // Detect if we are running on a faulty buggy OS.
  10691. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10692. // Detect if we are running on a faulty buggy desktop OS.
  10693. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10694. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10695. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10696. }
  10697. Object.defineProperty(Engine, "LastCreatedEngine", {
  10698. get: function () {
  10699. if (Engine.Instances.length === 0) {
  10700. return null;
  10701. }
  10702. return Engine.Instances[Engine.Instances.length - 1];
  10703. },
  10704. enumerable: true,
  10705. configurable: true
  10706. });
  10707. Object.defineProperty(Engine, "LastCreatedScene", {
  10708. get: function () {
  10709. var lastCreatedEngine = Engine.LastCreatedEngine;
  10710. if (!lastCreatedEngine) {
  10711. return null;
  10712. }
  10713. if (lastCreatedEngine.scenes.length === 0) {
  10714. return null;
  10715. }
  10716. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10717. },
  10718. enumerable: true,
  10719. configurable: true
  10720. });
  10721. /**
  10722. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10723. */
  10724. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10725. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10726. var engine = Engine.Instances[engineIndex];
  10727. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10728. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10729. }
  10730. }
  10731. };
  10732. Object.defineProperty(Engine, "NEVER", {
  10733. get: function () {
  10734. return Engine._NEVER;
  10735. },
  10736. enumerable: true,
  10737. configurable: true
  10738. });
  10739. Object.defineProperty(Engine, "ALWAYS", {
  10740. get: function () {
  10741. return Engine._ALWAYS;
  10742. },
  10743. enumerable: true,
  10744. configurable: true
  10745. });
  10746. Object.defineProperty(Engine, "LESS", {
  10747. get: function () {
  10748. return Engine._LESS;
  10749. },
  10750. enumerable: true,
  10751. configurable: true
  10752. });
  10753. Object.defineProperty(Engine, "EQUAL", {
  10754. get: function () {
  10755. return Engine._EQUAL;
  10756. },
  10757. enumerable: true,
  10758. configurable: true
  10759. });
  10760. Object.defineProperty(Engine, "LEQUAL", {
  10761. get: function () {
  10762. return Engine._LEQUAL;
  10763. },
  10764. enumerable: true,
  10765. configurable: true
  10766. });
  10767. Object.defineProperty(Engine, "GREATER", {
  10768. get: function () {
  10769. return Engine._GREATER;
  10770. },
  10771. enumerable: true,
  10772. configurable: true
  10773. });
  10774. Object.defineProperty(Engine, "GEQUAL", {
  10775. get: function () {
  10776. return Engine._GEQUAL;
  10777. },
  10778. enumerable: true,
  10779. configurable: true
  10780. });
  10781. Object.defineProperty(Engine, "NOTEQUAL", {
  10782. get: function () {
  10783. return Engine._NOTEQUAL;
  10784. },
  10785. enumerable: true,
  10786. configurable: true
  10787. });
  10788. Object.defineProperty(Engine, "KEEP", {
  10789. get: function () {
  10790. return Engine._KEEP;
  10791. },
  10792. enumerable: true,
  10793. configurable: true
  10794. });
  10795. Object.defineProperty(Engine, "REPLACE", {
  10796. get: function () {
  10797. return Engine._REPLACE;
  10798. },
  10799. enumerable: true,
  10800. configurable: true
  10801. });
  10802. Object.defineProperty(Engine, "INCR", {
  10803. get: function () {
  10804. return Engine._INCR;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(Engine, "DECR", {
  10810. get: function () {
  10811. return Engine._DECR;
  10812. },
  10813. enumerable: true,
  10814. configurable: true
  10815. });
  10816. Object.defineProperty(Engine, "INVERT", {
  10817. get: function () {
  10818. return Engine._INVERT;
  10819. },
  10820. enumerable: true,
  10821. configurable: true
  10822. });
  10823. Object.defineProperty(Engine, "INCR_WRAP", {
  10824. get: function () {
  10825. return Engine._INCR_WRAP;
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Object.defineProperty(Engine, "DECR_WRAP", {
  10831. get: function () {
  10832. return Engine._DECR_WRAP;
  10833. },
  10834. enumerable: true,
  10835. configurable: true
  10836. });
  10837. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10838. get: function () {
  10839. return Engine._ALPHA_DISABLE;
  10840. },
  10841. enumerable: true,
  10842. configurable: true
  10843. });
  10844. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10845. get: function () {
  10846. return Engine._ALPHA_ONEONE;
  10847. },
  10848. enumerable: true,
  10849. configurable: true
  10850. });
  10851. Object.defineProperty(Engine, "ALPHA_ADD", {
  10852. get: function () {
  10853. return Engine._ALPHA_ADD;
  10854. },
  10855. enumerable: true,
  10856. configurable: true
  10857. });
  10858. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10859. get: function () {
  10860. return Engine._ALPHA_COMBINE;
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10866. get: function () {
  10867. return Engine._ALPHA_SUBTRACT;
  10868. },
  10869. enumerable: true,
  10870. configurable: true
  10871. });
  10872. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10873. get: function () {
  10874. return Engine._ALPHA_MULTIPLY;
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10880. get: function () {
  10881. return Engine._ALPHA_MAXIMIZED;
  10882. },
  10883. enumerable: true,
  10884. configurable: true
  10885. });
  10886. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10887. get: function () {
  10888. return Engine._ALPHA_PREMULTIPLIED;
  10889. },
  10890. enumerable: true,
  10891. configurable: true
  10892. });
  10893. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10894. get: function () {
  10895. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10896. },
  10897. enumerable: true,
  10898. configurable: true
  10899. });
  10900. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10901. get: function () {
  10902. return Engine._ALPHA_INTERPOLATE;
  10903. },
  10904. enumerable: true,
  10905. configurable: true
  10906. });
  10907. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10908. get: function () {
  10909. return Engine._ALPHA_SCREENMODE;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10915. get: function () {
  10916. return Engine._DELAYLOADSTATE_NONE;
  10917. },
  10918. enumerable: true,
  10919. configurable: true
  10920. });
  10921. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10922. get: function () {
  10923. return Engine._DELAYLOADSTATE_LOADED;
  10924. },
  10925. enumerable: true,
  10926. configurable: true
  10927. });
  10928. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10929. get: function () {
  10930. return Engine._DELAYLOADSTATE_LOADING;
  10931. },
  10932. enumerable: true,
  10933. configurable: true
  10934. });
  10935. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10936. get: function () {
  10937. return Engine._DELAYLOADSTATE_NOTLOADED;
  10938. },
  10939. enumerable: true,
  10940. configurable: true
  10941. });
  10942. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10943. get: function () {
  10944. return Engine._TEXTUREFORMAT_ALPHA;
  10945. },
  10946. enumerable: true,
  10947. configurable: true
  10948. });
  10949. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10950. get: function () {
  10951. return Engine._TEXTUREFORMAT_LUMINANCE;
  10952. },
  10953. enumerable: true,
  10954. configurable: true
  10955. });
  10956. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10957. /**
  10958. * R32F
  10959. */
  10960. get: function () {
  10961. return Engine._TEXTUREFORMAT_R32F;
  10962. },
  10963. enumerable: true,
  10964. configurable: true
  10965. });
  10966. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10967. /**
  10968. * RG32F
  10969. */
  10970. get: function () {
  10971. return Engine._TEXTUREFORMAT_RG32F;
  10972. },
  10973. enumerable: true,
  10974. configurable: true
  10975. });
  10976. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  10977. /**
  10978. * RGB32F
  10979. */
  10980. get: function () {
  10981. return Engine._TEXTUREFORMAT_RGB32F;
  10982. },
  10983. enumerable: true,
  10984. configurable: true
  10985. });
  10986. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  10987. /**
  10988. * RGBA32F
  10989. */
  10990. get: function () {
  10991. return Engine._TEXTUREFORMAT_RGBA32F;
  10992. },
  10993. enumerable: true,
  10994. configurable: true
  10995. });
  10996. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10997. get: function () {
  10998. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10999. },
  11000. enumerable: true,
  11001. configurable: true
  11002. });
  11003. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11004. get: function () {
  11005. return Engine._TEXTUREFORMAT_RGB;
  11006. },
  11007. enumerable: true,
  11008. configurable: true
  11009. });
  11010. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11011. get: function () {
  11012. return Engine._TEXTUREFORMAT_RGBA;
  11013. },
  11014. enumerable: true,
  11015. configurable: true
  11016. });
  11017. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11018. get: function () {
  11019. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11020. },
  11021. enumerable: true,
  11022. configurable: true
  11023. });
  11024. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11025. get: function () {
  11026. return Engine._TEXTURETYPE_FLOAT;
  11027. },
  11028. enumerable: true,
  11029. configurable: true
  11030. });
  11031. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11032. get: function () {
  11033. return Engine._TEXTURETYPE_HALF_FLOAT;
  11034. },
  11035. enumerable: true,
  11036. configurable: true
  11037. });
  11038. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11039. get: function () {
  11040. return Engine._SCALEMODE_FLOOR;
  11041. },
  11042. enumerable: true,
  11043. configurable: true
  11044. });
  11045. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11046. get: function () {
  11047. return Engine._SCALEMODE_NEAREST;
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11053. get: function () {
  11054. return Engine._SCALEMODE_CEILING;
  11055. },
  11056. enumerable: true,
  11057. configurable: true
  11058. });
  11059. Object.defineProperty(Engine, "Version", {
  11060. get: function () {
  11061. return "3.2.0-alphaB";
  11062. },
  11063. enumerable: true,
  11064. configurable: true
  11065. });
  11066. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11067. get: function () {
  11068. return this._vrExclusivePointerMode;
  11069. },
  11070. enumerable: true,
  11071. configurable: true
  11072. });
  11073. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11074. get: function () {
  11075. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11076. },
  11077. enumerable: true,
  11078. configurable: true
  11079. });
  11080. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11081. get: function () {
  11082. return this._webGLVersion < 2 || this.forcePOTTextures;
  11083. },
  11084. enumerable: true,
  11085. configurable: true
  11086. });
  11087. Object.defineProperty(Engine.prototype, "badOS", {
  11088. get: function () {
  11089. return this._badOS;
  11090. },
  11091. enumerable: true,
  11092. configurable: true
  11093. });
  11094. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11095. get: function () {
  11096. return this._badDesktopOS;
  11097. },
  11098. enumerable: true,
  11099. configurable: true
  11100. });
  11101. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11102. get: function () {
  11103. return this._performanceMonitor;
  11104. },
  11105. enumerable: true,
  11106. configurable: true
  11107. });
  11108. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11109. get: function () {
  11110. return this._texturesSupported;
  11111. },
  11112. enumerable: true,
  11113. configurable: true
  11114. });
  11115. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11116. get: function () {
  11117. return this._textureFormatInUse;
  11118. },
  11119. enumerable: true,
  11120. configurable: true
  11121. });
  11122. Object.defineProperty(Engine.prototype, "currentViewport", {
  11123. get: function () {
  11124. return this._cachedViewport;
  11125. },
  11126. enumerable: true,
  11127. configurable: true
  11128. });
  11129. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11130. // Empty texture
  11131. get: function () {
  11132. if (!this._emptyTexture) {
  11133. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11134. }
  11135. return this._emptyTexture;
  11136. },
  11137. enumerable: true,
  11138. configurable: true
  11139. });
  11140. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11141. get: function () {
  11142. if (!this._emptyTexture3D) {
  11143. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11144. }
  11145. return this._emptyTexture3D;
  11146. },
  11147. enumerable: true,
  11148. configurable: true
  11149. });
  11150. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11151. get: function () {
  11152. if (!this._emptyCubeTexture) {
  11153. var faceData = new Uint8Array(4);
  11154. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11155. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11156. }
  11157. return this._emptyCubeTexture;
  11158. },
  11159. enumerable: true,
  11160. configurable: true
  11161. });
  11162. Engine.prototype._rebuildInternalTextures = function () {
  11163. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11164. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11165. var internalTexture = currentState_1[_i];
  11166. internalTexture._rebuild();
  11167. }
  11168. };
  11169. Engine.prototype._rebuildEffects = function () {
  11170. for (var key in this._compiledEffects) {
  11171. var effect = this._compiledEffects[key];
  11172. effect._prepareEffect();
  11173. }
  11174. BABYLON.Effect.ResetCache();
  11175. };
  11176. Engine.prototype._rebuildBuffers = function () {
  11177. // Index / Vertex
  11178. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11179. var scene = _a[_i];
  11180. scene.resetCachedMaterial();
  11181. scene._rebuildGeometries();
  11182. scene._rebuildTextures();
  11183. }
  11184. // Uniforms
  11185. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11186. var uniformBuffer = _c[_b];
  11187. uniformBuffer._rebuild();
  11188. }
  11189. };
  11190. Engine.prototype._initGLContext = function () {
  11191. // Caps
  11192. this._caps = new EngineCapabilities();
  11193. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11194. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11195. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11196. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11197. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11198. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11199. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11200. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11201. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11202. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11203. // Infos
  11204. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11205. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11206. if (rendererInfo != null) {
  11207. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11208. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11209. }
  11210. if (!this._glVendor) {
  11211. this._glVendor = "Unknown vendor";
  11212. }
  11213. if (!this._glRenderer) {
  11214. this._glRenderer = "Unknown renderer";
  11215. }
  11216. // Constants
  11217. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11218. if (this._gl.RGBA16F !== 0x881A) {
  11219. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11220. }
  11221. if (this._gl.RGBA32F !== 0x8814) {
  11222. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11223. }
  11224. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11225. this._gl.DEPTH24_STENCIL8 = 35056;
  11226. }
  11227. // Extensions
  11228. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11229. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11230. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11231. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11232. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11233. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11234. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11235. 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');
  11236. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11237. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11238. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11239. this._caps.highPrecisionShaderSupported = true;
  11240. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11241. if (this._caps.timerQuery) {
  11242. if (this._webGLVersion === 1) {
  11243. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11244. }
  11245. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11246. }
  11247. // Checks if some of the format renders first to allow the use of webgl inspector.
  11248. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11249. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11250. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11251. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11252. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11253. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11254. if (this._webGLVersion > 1) {
  11255. this._gl.HALF_FLOAT_OES = 0x140B;
  11256. }
  11257. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11258. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11259. // Draw buffers
  11260. if (this._webGLVersion > 1) {
  11261. this._caps.drawBuffersExtension = true;
  11262. }
  11263. else {
  11264. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11265. if (drawBuffersExtension !== null) {
  11266. this._caps.drawBuffersExtension = true;
  11267. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11268. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11269. for (var i = 0; i < 16; i++) {
  11270. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11271. }
  11272. }
  11273. else {
  11274. this._caps.drawBuffersExtension = false;
  11275. }
  11276. }
  11277. // Depth Texture
  11278. if (this._webGLVersion > 1) {
  11279. this._caps.depthTextureExtension = true;
  11280. }
  11281. else {
  11282. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11283. if (depthTextureExtension != null) {
  11284. this._caps.depthTextureExtension = true;
  11285. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11286. }
  11287. }
  11288. // Vertex array object
  11289. if (this._webGLVersion > 1) {
  11290. this._caps.vertexArrayObject = true;
  11291. }
  11292. else {
  11293. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11294. if (vertexArrayObjectExtension != null) {
  11295. this._caps.vertexArrayObject = true;
  11296. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11297. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11298. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11299. }
  11300. else {
  11301. this._caps.vertexArrayObject = false;
  11302. }
  11303. }
  11304. // Instances count
  11305. if (this._webGLVersion > 1) {
  11306. this._caps.instancedArrays = true;
  11307. }
  11308. else {
  11309. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11310. if (instanceExtension != null) {
  11311. this._caps.instancedArrays = true;
  11312. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11313. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11314. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11315. }
  11316. else {
  11317. this._caps.instancedArrays = false;
  11318. }
  11319. }
  11320. // Intelligently add supported compressed formats in order to check for.
  11321. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11322. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11323. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11324. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11325. if (this._caps.astc)
  11326. this.texturesSupported.push('-astc.ktx');
  11327. if (this._caps.s3tc)
  11328. this.texturesSupported.push('-dxt.ktx');
  11329. if (this._caps.pvrtc)
  11330. this.texturesSupported.push('-pvrtc.ktx');
  11331. if (this._caps.etc2)
  11332. this.texturesSupported.push('-etc2.ktx');
  11333. if (this._caps.etc1)
  11334. this.texturesSupported.push('-etc1.ktx');
  11335. if (this._gl.getShaderPrecisionFormat) {
  11336. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11337. if (highp) {
  11338. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11339. }
  11340. }
  11341. // Depth buffer
  11342. this.setDepthBuffer(true);
  11343. this.setDepthFunctionToLessOrEqual();
  11344. this.setDepthWrite(true);
  11345. // Texture maps
  11346. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11347. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11348. this._nextFreeTextureSlots.push(slot);
  11349. }
  11350. };
  11351. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11352. get: function () {
  11353. return this._webGLVersion;
  11354. },
  11355. enumerable: true,
  11356. configurable: true
  11357. });
  11358. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11359. /**
  11360. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11361. */
  11362. get: function () {
  11363. return this._isStencilEnable;
  11364. },
  11365. enumerable: true,
  11366. configurable: true
  11367. });
  11368. Engine.prototype._prepareWorkingCanvas = function () {
  11369. if (this._workingCanvas) {
  11370. return;
  11371. }
  11372. this._workingCanvas = document.createElement("canvas");
  11373. var context = this._workingCanvas.getContext("2d");
  11374. if (context) {
  11375. this._workingContext = context;
  11376. }
  11377. };
  11378. Engine.prototype.resetTextureCache = function () {
  11379. for (var key in this._boundTexturesCache) {
  11380. var boundTexture = this._boundTexturesCache[key];
  11381. if (boundTexture) {
  11382. this._removeDesignatedSlot(boundTexture);
  11383. }
  11384. this._boundTexturesCache[key] = null;
  11385. }
  11386. if (!this.disableTextureBindingOptimization) {
  11387. this._nextFreeTextureSlots = [];
  11388. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11389. this._nextFreeTextureSlots.push(slot);
  11390. }
  11391. }
  11392. this._currentTextureChannel = -1;
  11393. };
  11394. Engine.prototype.isDeterministicLockStep = function () {
  11395. return this._deterministicLockstep;
  11396. };
  11397. Engine.prototype.getLockstepMaxSteps = function () {
  11398. return this._lockstepMaxSteps;
  11399. };
  11400. Engine.prototype.getGlInfo = function () {
  11401. return {
  11402. vendor: this._glVendor,
  11403. renderer: this._glRenderer,
  11404. version: this._glVersion
  11405. };
  11406. };
  11407. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11408. if (useScreen === void 0) { useScreen = false; }
  11409. var viewport = camera.viewport;
  11410. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11411. };
  11412. Engine.prototype.getRenderWidth = function (useScreen) {
  11413. if (useScreen === void 0) { useScreen = false; }
  11414. if (!useScreen && this._currentRenderTarget) {
  11415. return this._currentRenderTarget.width;
  11416. }
  11417. return this._gl.drawingBufferWidth;
  11418. };
  11419. Engine.prototype.getRenderHeight = function (useScreen) {
  11420. if (useScreen === void 0) { useScreen = false; }
  11421. if (!useScreen && this._currentRenderTarget) {
  11422. return this._currentRenderTarget.height;
  11423. }
  11424. return this._gl.drawingBufferHeight;
  11425. };
  11426. Engine.prototype.getRenderingCanvas = function () {
  11427. return this._renderingCanvas;
  11428. };
  11429. Engine.prototype.getRenderingCanvasClientRect = function () {
  11430. if (!this._renderingCanvas) {
  11431. return null;
  11432. }
  11433. return this._renderingCanvas.getBoundingClientRect();
  11434. };
  11435. Engine.prototype.setHardwareScalingLevel = function (level) {
  11436. this._hardwareScalingLevel = level;
  11437. this.resize();
  11438. };
  11439. Engine.prototype.getHardwareScalingLevel = function () {
  11440. return this._hardwareScalingLevel;
  11441. };
  11442. Engine.prototype.getLoadedTexturesCache = function () {
  11443. return this._internalTexturesCache;
  11444. };
  11445. Engine.prototype.getCaps = function () {
  11446. return this._caps;
  11447. };
  11448. Object.defineProperty(Engine.prototype, "drawCalls", {
  11449. /** The number of draw calls submitted last frame */
  11450. get: function () {
  11451. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11452. return 0;
  11453. },
  11454. enumerable: true,
  11455. configurable: true
  11456. });
  11457. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11458. get: function () {
  11459. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11460. return null;
  11461. },
  11462. enumerable: true,
  11463. configurable: true
  11464. });
  11465. Engine.prototype.getDepthFunction = function () {
  11466. return this._depthCullingState.depthFunc;
  11467. };
  11468. Engine.prototype.setDepthFunction = function (depthFunc) {
  11469. this._depthCullingState.depthFunc = depthFunc;
  11470. };
  11471. Engine.prototype.setDepthFunctionToGreater = function () {
  11472. this._depthCullingState.depthFunc = this._gl.GREATER;
  11473. };
  11474. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11475. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11476. };
  11477. Engine.prototype.setDepthFunctionToLess = function () {
  11478. this._depthCullingState.depthFunc = this._gl.LESS;
  11479. };
  11480. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11481. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11482. };
  11483. Engine.prototype.getStencilBuffer = function () {
  11484. return this._stencilState.stencilTest;
  11485. };
  11486. Engine.prototype.setStencilBuffer = function (enable) {
  11487. this._stencilState.stencilTest = enable;
  11488. };
  11489. Engine.prototype.getStencilMask = function () {
  11490. return this._stencilState.stencilMask;
  11491. };
  11492. Engine.prototype.setStencilMask = function (mask) {
  11493. this._stencilState.stencilMask = mask;
  11494. };
  11495. Engine.prototype.getStencilFunction = function () {
  11496. return this._stencilState.stencilFunc;
  11497. };
  11498. Engine.prototype.getStencilFunctionReference = function () {
  11499. return this._stencilState.stencilFuncRef;
  11500. };
  11501. Engine.prototype.getStencilFunctionMask = function () {
  11502. return this._stencilState.stencilFuncMask;
  11503. };
  11504. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11505. this._stencilState.stencilFunc = stencilFunc;
  11506. };
  11507. Engine.prototype.setStencilFunctionReference = function (reference) {
  11508. this._stencilState.stencilFuncRef = reference;
  11509. };
  11510. Engine.prototype.setStencilFunctionMask = function (mask) {
  11511. this._stencilState.stencilFuncMask = mask;
  11512. };
  11513. Engine.prototype.getStencilOperationFail = function () {
  11514. return this._stencilState.stencilOpStencilFail;
  11515. };
  11516. Engine.prototype.getStencilOperationDepthFail = function () {
  11517. return this._stencilState.stencilOpDepthFail;
  11518. };
  11519. Engine.prototype.getStencilOperationPass = function () {
  11520. return this._stencilState.stencilOpStencilDepthPass;
  11521. };
  11522. Engine.prototype.setStencilOperationFail = function (operation) {
  11523. this._stencilState.stencilOpStencilFail = operation;
  11524. };
  11525. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11526. this._stencilState.stencilOpDepthFail = operation;
  11527. };
  11528. Engine.prototype.setStencilOperationPass = function (operation) {
  11529. this._stencilState.stencilOpStencilDepthPass = operation;
  11530. };
  11531. Engine.prototype.setDitheringState = function (value) {
  11532. if (value) {
  11533. this._gl.enable(this._gl.DITHER);
  11534. }
  11535. else {
  11536. this._gl.disable(this._gl.DITHER);
  11537. }
  11538. };
  11539. Engine.prototype.setRasterizerState = function (value) {
  11540. if (value) {
  11541. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11542. }
  11543. else {
  11544. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11545. }
  11546. };
  11547. /**
  11548. * stop executing a render loop function and remove it from the execution array
  11549. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11550. */
  11551. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11552. if (!renderFunction) {
  11553. this._activeRenderLoops = [];
  11554. return;
  11555. }
  11556. var index = this._activeRenderLoops.indexOf(renderFunction);
  11557. if (index >= 0) {
  11558. this._activeRenderLoops.splice(index, 1);
  11559. }
  11560. };
  11561. Engine.prototype._renderLoop = function () {
  11562. if (!this._contextWasLost) {
  11563. var shouldRender = true;
  11564. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11565. shouldRender = false;
  11566. }
  11567. if (shouldRender) {
  11568. // Start new frame
  11569. this.beginFrame();
  11570. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11571. var renderFunction = this._activeRenderLoops[index];
  11572. renderFunction();
  11573. }
  11574. // Present
  11575. this.endFrame();
  11576. }
  11577. }
  11578. if (this._activeRenderLoops.length > 0) {
  11579. // Register new frame
  11580. var requester = null;
  11581. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11582. requester = this._vrDisplay;
  11583. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11584. }
  11585. else {
  11586. this._renderingQueueLaunched = false;
  11587. }
  11588. };
  11589. /**
  11590. * Register and execute a render loop. The engine can have more than one render function.
  11591. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11592. * @example
  11593. * engine.runRenderLoop(function () {
  11594. * scene.render()
  11595. * })
  11596. */
  11597. Engine.prototype.runRenderLoop = function (renderFunction) {
  11598. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11599. return;
  11600. }
  11601. this._activeRenderLoops.push(renderFunction);
  11602. if (!this._renderingQueueLaunched) {
  11603. this._renderingQueueLaunched = true;
  11604. this._bindedRenderFunction = this._renderLoop.bind(this);
  11605. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11606. }
  11607. };
  11608. /**
  11609. * Toggle full screen mode.
  11610. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11611. * @param {any} options - an options object to be sent to the requestFullscreen function
  11612. */
  11613. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11614. if (this.isFullscreen) {
  11615. BABYLON.Tools.ExitFullscreen();
  11616. }
  11617. else {
  11618. this._pointerLockRequested = requestPointerLock;
  11619. if (this._renderingCanvas) {
  11620. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11621. }
  11622. }
  11623. };
  11624. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11625. if (stencil === void 0) { stencil = false; }
  11626. this.applyStates();
  11627. var mode = 0;
  11628. if (backBuffer && color) {
  11629. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11630. mode |= this._gl.COLOR_BUFFER_BIT;
  11631. }
  11632. if (depth) {
  11633. this._gl.clearDepth(1.0);
  11634. mode |= this._gl.DEPTH_BUFFER_BIT;
  11635. }
  11636. if (stencil) {
  11637. this._gl.clearStencil(0);
  11638. mode |= this._gl.STENCIL_BUFFER_BIT;
  11639. }
  11640. this._gl.clear(mode);
  11641. };
  11642. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11643. var gl = this._gl;
  11644. // Save state
  11645. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11646. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11647. // Change state
  11648. gl.enable(gl.SCISSOR_TEST);
  11649. gl.scissor(x, y, width, height);
  11650. // Clear
  11651. this.clear(clearColor, true, true, true);
  11652. // Restore state
  11653. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11654. if (curScissor === true) {
  11655. gl.enable(gl.SCISSOR_TEST);
  11656. }
  11657. else {
  11658. gl.disable(gl.SCISSOR_TEST);
  11659. }
  11660. };
  11661. /**
  11662. * Set the WebGL's viewport
  11663. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11664. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11665. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11666. */
  11667. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11668. var width = requiredWidth || this.getRenderWidth();
  11669. var height = requiredHeight || this.getRenderHeight();
  11670. var x = viewport.x || 0;
  11671. var y = viewport.y || 0;
  11672. this._cachedViewport = viewport;
  11673. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11674. };
  11675. /**
  11676. * Directly set the WebGL Viewport
  11677. * The x, y, width & height are directly passed to the WebGL call
  11678. * @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.
  11679. */
  11680. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11681. var currentViewport = this._cachedViewport;
  11682. this._cachedViewport = null;
  11683. this._gl.viewport(x, y, width, height);
  11684. return currentViewport;
  11685. };
  11686. Engine.prototype.beginFrame = function () {
  11687. this.onBeginFrameObservable.notifyObservers(this);
  11688. this._measureFps();
  11689. };
  11690. Engine.prototype.endFrame = function () {
  11691. //force a flush in case we are using a bad OS.
  11692. if (this._badOS) {
  11693. this.flushFramebuffer();
  11694. }
  11695. //submit frame to the vr device, if enabled
  11696. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11697. // TODO: We should only submit the frame if we read frameData successfully.
  11698. this._vrDisplay.submitFrame();
  11699. }
  11700. this.onEndFrameObservable.notifyObservers(this);
  11701. };
  11702. /**
  11703. * resize the view according to the canvas' size.
  11704. * @example
  11705. * window.addEventListener("resize", function () {
  11706. * engine.resize();
  11707. * });
  11708. */
  11709. Engine.prototype.resize = function () {
  11710. // We're not resizing the size of the canvas while in VR mode & presenting
  11711. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11712. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11713. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11714. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11715. }
  11716. };
  11717. /**
  11718. * force a specific size of the canvas
  11719. * @param {number} width - the new canvas' width
  11720. * @param {number} height - the new canvas' height
  11721. */
  11722. Engine.prototype.setSize = function (width, height) {
  11723. if (!this._renderingCanvas) {
  11724. return;
  11725. }
  11726. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11727. return;
  11728. }
  11729. this._renderingCanvas.width = width;
  11730. this._renderingCanvas.height = height;
  11731. for (var index = 0; index < this.scenes.length; index++) {
  11732. var scene = this.scenes[index];
  11733. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11734. var cam = scene.cameras[camIndex];
  11735. cam._currentRenderId = 0;
  11736. }
  11737. }
  11738. if (this.onResizeObservable.hasObservers) {
  11739. this.onResizeObservable.notifyObservers(this);
  11740. }
  11741. };
  11742. // WebVR functions
  11743. Engine.prototype.isVRDevicePresent = function () {
  11744. return !!this._vrDisplay;
  11745. };
  11746. Engine.prototype.getVRDevice = function () {
  11747. return this._vrDisplay;
  11748. };
  11749. /**
  11750. * Initializes a webVR display and starts listening to display change events.
  11751. * The onVRDisplayChangedObservable will be notified upon these changes.
  11752. * @returns The onVRDisplayChangedObservable.
  11753. */
  11754. Engine.prototype.initWebVR = function () {
  11755. this.initWebVRAsync();
  11756. return this.onVRDisplayChangedObservable;
  11757. };
  11758. /**
  11759. * Initializes a webVR display and starts listening to display change events.
  11760. * The onVRDisplayChangedObservable will be notified upon these changes.
  11761. * @returns A promise containing a VRDisplay and if vr is supported.
  11762. */
  11763. Engine.prototype.initWebVRAsync = function () {
  11764. var _this = this;
  11765. var notifyObservers = function () {
  11766. var eventArgs = {
  11767. vrDisplay: _this._vrDisplay,
  11768. vrSupported: _this._vrSupported
  11769. };
  11770. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11771. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11772. };
  11773. if (!this._onVrDisplayConnect) {
  11774. this._onVrDisplayConnect = function (event) {
  11775. _this._vrDisplay = event.display;
  11776. notifyObservers();
  11777. };
  11778. this._onVrDisplayDisconnect = function () {
  11779. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11780. _this._vrDisplay = undefined;
  11781. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11782. notifyObservers();
  11783. };
  11784. this._onVrDisplayPresentChange = function () {
  11785. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11786. };
  11787. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11788. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11789. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11790. }
  11791. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11792. this._webVRInitPromise.then(notifyObservers);
  11793. return this._webVRInitPromise;
  11794. };
  11795. Engine.prototype.enableVR = function () {
  11796. var _this = this;
  11797. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11798. var onResolved = function () {
  11799. _this.onVRRequestPresentComplete.notifyObservers(true);
  11800. _this._onVRFullScreenTriggered();
  11801. };
  11802. var onRejected = function () {
  11803. _this.onVRRequestPresentComplete.notifyObservers(false);
  11804. };
  11805. this.onVRRequestPresentStart.notifyObservers(this);
  11806. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11807. }
  11808. };
  11809. Engine.prototype.disableVR = function () {
  11810. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11811. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11812. }
  11813. };
  11814. Engine.prototype._getVRDisplaysAsync = function () {
  11815. var _this = this;
  11816. return new Promise(function (res, rej) {
  11817. if (navigator.getVRDisplays) {
  11818. navigator.getVRDisplays().then(function (devices) {
  11819. _this._vrSupported = true;
  11820. // note that devices may actually be an empty array. This is fine;
  11821. // we expect this._vrDisplay to be undefined in this case.
  11822. _this._vrDisplay = devices[0];
  11823. res({
  11824. vrDisplay: _this._vrDisplay,
  11825. vrSupported: _this._vrSupported
  11826. });
  11827. });
  11828. }
  11829. else {
  11830. _this._vrDisplay = undefined;
  11831. _this._vrSupported = false;
  11832. res({
  11833. vrDisplay: _this._vrDisplay,
  11834. vrSupported: _this._vrSupported
  11835. });
  11836. }
  11837. });
  11838. };
  11839. /**
  11840. * Binds the frame buffer to the specified texture.
  11841. * @param texture The texture to render to or null for the default canvas
  11842. * @param faceIndex The face of the texture to render to in case of cube texture
  11843. * @param requiredWidth The width of the target to render to
  11844. * @param requiredHeight The height of the target to render to
  11845. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11846. * @param depthStencilTexture The depth stencil texture to use to render
  11847. */
  11848. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11849. if (this._currentRenderTarget) {
  11850. this.unBindFramebuffer(this._currentRenderTarget);
  11851. }
  11852. this._currentRenderTarget = texture;
  11853. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11854. var gl = this._gl;
  11855. if (texture.isCube) {
  11856. if (faceIndex === undefined) {
  11857. faceIndex = 0;
  11858. }
  11859. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11860. if (depthStencilTexture) {
  11861. if (depthStencilTexture._generateStencilBuffer) {
  11862. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11863. }
  11864. else {
  11865. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11866. }
  11867. }
  11868. }
  11869. if (this._cachedViewport && !forceFullscreenViewport) {
  11870. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11871. }
  11872. else {
  11873. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11874. }
  11875. this.wipeCaches();
  11876. };
  11877. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11878. if (this._currentFramebuffer !== framebuffer) {
  11879. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11880. this._currentFramebuffer = framebuffer;
  11881. }
  11882. };
  11883. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11884. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11885. this._currentRenderTarget = null;
  11886. // If MSAA, we need to bitblt back to main texture
  11887. var gl = this._gl;
  11888. if (texture._MSAAFramebuffer) {
  11889. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11890. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11891. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11892. }
  11893. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11894. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11895. gl.generateMipmap(gl.TEXTURE_2D);
  11896. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11897. }
  11898. if (onBeforeUnbind) {
  11899. if (texture._MSAAFramebuffer) {
  11900. // Bind the correct framebuffer
  11901. this.bindUnboundFramebuffer(texture._framebuffer);
  11902. }
  11903. onBeforeUnbind();
  11904. }
  11905. this.bindUnboundFramebuffer(null);
  11906. };
  11907. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11908. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11909. this._currentRenderTarget = null;
  11910. // If MSAA, we need to bitblt back to main texture
  11911. var gl = this._gl;
  11912. if (textures[0]._MSAAFramebuffer) {
  11913. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11914. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11915. var attachments = textures[0]._attachments;
  11916. if (!attachments) {
  11917. attachments = new Array(textures.length);
  11918. textures[0]._attachments = attachments;
  11919. }
  11920. for (var i = 0; i < textures.length; i++) {
  11921. var texture = textures[i];
  11922. for (var j = 0; j < attachments.length; j++) {
  11923. attachments[j] = gl.NONE;
  11924. }
  11925. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11926. gl.readBuffer(attachments[i]);
  11927. gl.drawBuffers(attachments);
  11928. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11929. }
  11930. for (var i = 0; i < attachments.length; i++) {
  11931. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11932. }
  11933. gl.drawBuffers(attachments);
  11934. }
  11935. for (var i = 0; i < textures.length; i++) {
  11936. var texture = textures[i];
  11937. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11938. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11939. gl.generateMipmap(gl.TEXTURE_2D);
  11940. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11941. }
  11942. }
  11943. if (onBeforeUnbind) {
  11944. if (textures[0]._MSAAFramebuffer) {
  11945. // Bind the correct framebuffer
  11946. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11947. }
  11948. onBeforeUnbind();
  11949. }
  11950. this.bindUnboundFramebuffer(null);
  11951. };
  11952. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11953. if (texture.generateMipMaps) {
  11954. var gl = this._gl;
  11955. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11956. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11957. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11958. }
  11959. };
  11960. Engine.prototype.flushFramebuffer = function () {
  11961. this._gl.flush();
  11962. };
  11963. Engine.prototype.restoreDefaultFramebuffer = function () {
  11964. if (this._currentRenderTarget) {
  11965. this.unBindFramebuffer(this._currentRenderTarget);
  11966. }
  11967. else {
  11968. this.bindUnboundFramebuffer(null);
  11969. }
  11970. if (this._cachedViewport) {
  11971. this.setViewport(this._cachedViewport);
  11972. }
  11973. this.wipeCaches();
  11974. };
  11975. // UBOs
  11976. Engine.prototype.createUniformBuffer = function (elements) {
  11977. var ubo = this._gl.createBuffer();
  11978. if (!ubo) {
  11979. throw new Error("Unable to create uniform buffer");
  11980. }
  11981. this.bindUniformBuffer(ubo);
  11982. if (elements instanceof Float32Array) {
  11983. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11984. }
  11985. else {
  11986. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11987. }
  11988. this.bindUniformBuffer(null);
  11989. ubo.references = 1;
  11990. return ubo;
  11991. };
  11992. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11993. var ubo = this._gl.createBuffer();
  11994. if (!ubo) {
  11995. throw new Error("Unable to create dynamic uniform buffer");
  11996. }
  11997. this.bindUniformBuffer(ubo);
  11998. if (elements instanceof Float32Array) {
  11999. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12000. }
  12001. else {
  12002. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12003. }
  12004. this.bindUniformBuffer(null);
  12005. ubo.references = 1;
  12006. return ubo;
  12007. };
  12008. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12009. this.bindUniformBuffer(uniformBuffer);
  12010. if (offset === undefined) {
  12011. offset = 0;
  12012. }
  12013. if (count === undefined) {
  12014. if (elements instanceof Float32Array) {
  12015. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12016. }
  12017. else {
  12018. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12019. }
  12020. }
  12021. else {
  12022. if (elements instanceof Float32Array) {
  12023. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12024. }
  12025. else {
  12026. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12027. }
  12028. }
  12029. this.bindUniformBuffer(null);
  12030. };
  12031. // VBOs
  12032. Engine.prototype._resetVertexBufferBinding = function () {
  12033. this.bindArrayBuffer(null);
  12034. this._cachedVertexBuffers = null;
  12035. };
  12036. Engine.prototype.createVertexBuffer = function (vertices) {
  12037. var vbo = this._gl.createBuffer();
  12038. if (!vbo) {
  12039. throw new Error("Unable to create vertex buffer");
  12040. }
  12041. this.bindArrayBuffer(vbo);
  12042. if (vertices instanceof Float32Array) {
  12043. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12044. }
  12045. else {
  12046. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12047. }
  12048. this._resetVertexBufferBinding();
  12049. vbo.references = 1;
  12050. return vbo;
  12051. };
  12052. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12053. var vbo = this._gl.createBuffer();
  12054. if (!vbo) {
  12055. throw new Error("Unable to create dynamic vertex buffer");
  12056. }
  12057. this.bindArrayBuffer(vbo);
  12058. if (vertices instanceof Float32Array) {
  12059. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12060. }
  12061. else {
  12062. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12063. }
  12064. this._resetVertexBufferBinding();
  12065. vbo.references = 1;
  12066. return vbo;
  12067. };
  12068. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12069. if (offset === void 0) { offset = 0; }
  12070. // Force cache update
  12071. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12072. this.bindIndexBuffer(indexBuffer);
  12073. var arrayBuffer;
  12074. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12075. arrayBuffer = indices;
  12076. }
  12077. else {
  12078. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12079. }
  12080. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12081. this._resetIndexBufferBinding();
  12082. };
  12083. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12084. this.bindArrayBuffer(vertexBuffer);
  12085. if (offset === undefined) {
  12086. offset = 0;
  12087. }
  12088. if (count === undefined) {
  12089. if (vertices instanceof Float32Array) {
  12090. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12091. }
  12092. else {
  12093. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12094. }
  12095. }
  12096. else {
  12097. if (vertices instanceof Float32Array) {
  12098. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12099. }
  12100. else {
  12101. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12102. }
  12103. }
  12104. this._resetVertexBufferBinding();
  12105. };
  12106. Engine.prototype._resetIndexBufferBinding = function () {
  12107. this.bindIndexBuffer(null);
  12108. this._cachedIndexBuffer = null;
  12109. };
  12110. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12111. var vbo = this._gl.createBuffer();
  12112. if (!vbo) {
  12113. throw new Error("Unable to create index buffer");
  12114. }
  12115. this.bindIndexBuffer(vbo);
  12116. // Check for 32 bits indices
  12117. var arrayBuffer;
  12118. var need32Bits = false;
  12119. if (indices instanceof Uint16Array) {
  12120. arrayBuffer = indices;
  12121. }
  12122. else {
  12123. //check 32 bit support
  12124. if (this._caps.uintIndices) {
  12125. if (indices instanceof Uint32Array) {
  12126. arrayBuffer = indices;
  12127. need32Bits = true;
  12128. }
  12129. else {
  12130. //number[] or Int32Array, check if 32 bit is necessary
  12131. for (var index = 0; index < indices.length; index++) {
  12132. if (indices[index] > 65535) {
  12133. need32Bits = true;
  12134. break;
  12135. }
  12136. }
  12137. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12138. }
  12139. }
  12140. else {
  12141. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12142. arrayBuffer = new Uint16Array(indices);
  12143. }
  12144. }
  12145. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12146. this._resetIndexBufferBinding();
  12147. vbo.references = 1;
  12148. vbo.is32Bits = need32Bits;
  12149. return vbo;
  12150. };
  12151. Engine.prototype.bindArrayBuffer = function (buffer) {
  12152. if (!this._vaoRecordInProgress) {
  12153. this._unbindVertexArrayObject();
  12154. }
  12155. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12156. };
  12157. Engine.prototype.bindUniformBuffer = function (buffer) {
  12158. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12159. };
  12160. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12161. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12162. };
  12163. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12164. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12165. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12166. };
  12167. ;
  12168. Engine.prototype.bindIndexBuffer = function (buffer) {
  12169. if (!this._vaoRecordInProgress) {
  12170. this._unbindVertexArrayObject();
  12171. }
  12172. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12173. };
  12174. Engine.prototype.bindBuffer = function (buffer, target) {
  12175. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12176. this._gl.bindBuffer(target, buffer);
  12177. this._currentBoundBuffer[target] = buffer;
  12178. }
  12179. };
  12180. Engine.prototype.updateArrayBuffer = function (data) {
  12181. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12182. };
  12183. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12184. var pointer = this._currentBufferPointers[indx];
  12185. var changed = false;
  12186. if (!pointer.active) {
  12187. changed = true;
  12188. pointer.active = true;
  12189. pointer.index = indx;
  12190. pointer.size = size;
  12191. pointer.type = type;
  12192. pointer.normalized = normalized;
  12193. pointer.stride = stride;
  12194. pointer.offset = offset;
  12195. pointer.buffer = buffer;
  12196. }
  12197. else {
  12198. if (pointer.buffer !== buffer) {
  12199. pointer.buffer = buffer;
  12200. changed = true;
  12201. }
  12202. if (pointer.size !== size) {
  12203. pointer.size = size;
  12204. changed = true;
  12205. }
  12206. if (pointer.type !== type) {
  12207. pointer.type = type;
  12208. changed = true;
  12209. }
  12210. if (pointer.normalized !== normalized) {
  12211. pointer.normalized = normalized;
  12212. changed = true;
  12213. }
  12214. if (pointer.stride !== stride) {
  12215. pointer.stride = stride;
  12216. changed = true;
  12217. }
  12218. if (pointer.offset !== offset) {
  12219. pointer.offset = offset;
  12220. changed = true;
  12221. }
  12222. }
  12223. if (changed || this._vaoRecordInProgress) {
  12224. this.bindArrayBuffer(buffer);
  12225. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12226. }
  12227. };
  12228. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12229. if (indexBuffer == null) {
  12230. return;
  12231. }
  12232. if (this._cachedIndexBuffer !== indexBuffer) {
  12233. this._cachedIndexBuffer = indexBuffer;
  12234. this.bindIndexBuffer(indexBuffer);
  12235. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12236. }
  12237. };
  12238. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12239. var attributes = effect.getAttributesNames();
  12240. if (!this._vaoRecordInProgress) {
  12241. this._unbindVertexArrayObject();
  12242. }
  12243. this.unbindAllAttributes();
  12244. for (var index = 0; index < attributes.length; index++) {
  12245. var order = effect.getAttributeLocation(index);
  12246. if (order >= 0) {
  12247. var vertexBuffer = vertexBuffers[attributes[index]];
  12248. if (!vertexBuffer) {
  12249. continue;
  12250. }
  12251. this._gl.enableVertexAttribArray(order);
  12252. if (!this._vaoRecordInProgress) {
  12253. this._vertexAttribArraysEnabled[order] = true;
  12254. }
  12255. var buffer = vertexBuffer.getBuffer();
  12256. if (buffer) {
  12257. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12258. if (vertexBuffer.getIsInstanced()) {
  12259. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12260. if (!this._vaoRecordInProgress) {
  12261. this._currentInstanceLocations.push(order);
  12262. this._currentInstanceBuffers.push(buffer);
  12263. }
  12264. }
  12265. }
  12266. }
  12267. }
  12268. };
  12269. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12270. var vao = this._gl.createVertexArray();
  12271. this._vaoRecordInProgress = true;
  12272. this._gl.bindVertexArray(vao);
  12273. this._mustWipeVertexAttributes = true;
  12274. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12275. this.bindIndexBuffer(indexBuffer);
  12276. this._vaoRecordInProgress = false;
  12277. this._gl.bindVertexArray(null);
  12278. return vao;
  12279. };
  12280. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12281. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12282. this._cachedVertexArrayObject = vertexArrayObject;
  12283. this._gl.bindVertexArray(vertexArrayObject);
  12284. this._cachedVertexBuffers = null;
  12285. this._cachedIndexBuffer = null;
  12286. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12287. this._mustWipeVertexAttributes = true;
  12288. }
  12289. };
  12290. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12291. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12292. this._cachedVertexBuffers = vertexBuffer;
  12293. this._cachedEffectForVertexBuffers = effect;
  12294. var attributesCount = effect.getAttributesCount();
  12295. this._unbindVertexArrayObject();
  12296. this.unbindAllAttributes();
  12297. var offset = 0;
  12298. for (var index = 0; index < attributesCount; index++) {
  12299. if (index < vertexDeclaration.length) {
  12300. var order = effect.getAttributeLocation(index);
  12301. if (order >= 0) {
  12302. this._gl.enableVertexAttribArray(order);
  12303. this._vertexAttribArraysEnabled[order] = true;
  12304. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12305. }
  12306. offset += vertexDeclaration[index] * 4;
  12307. }
  12308. }
  12309. }
  12310. this._bindIndexBufferWithCache(indexBuffer);
  12311. };
  12312. Engine.prototype._unbindVertexArrayObject = function () {
  12313. if (!this._cachedVertexArrayObject) {
  12314. return;
  12315. }
  12316. this._cachedVertexArrayObject = null;
  12317. this._gl.bindVertexArray(null);
  12318. };
  12319. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12320. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12321. this._cachedVertexBuffers = vertexBuffers;
  12322. this._cachedEffectForVertexBuffers = effect;
  12323. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12324. }
  12325. this._bindIndexBufferWithCache(indexBuffer);
  12326. };
  12327. Engine.prototype.unbindInstanceAttributes = function () {
  12328. var boundBuffer;
  12329. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12330. var instancesBuffer = this._currentInstanceBuffers[i];
  12331. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12332. boundBuffer = instancesBuffer;
  12333. this.bindArrayBuffer(instancesBuffer);
  12334. }
  12335. var offsetLocation = this._currentInstanceLocations[i];
  12336. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12337. }
  12338. this._currentInstanceBuffers.length = 0;
  12339. this._currentInstanceLocations.length = 0;
  12340. };
  12341. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12342. this._gl.deleteVertexArray(vao);
  12343. };
  12344. Engine.prototype._releaseBuffer = function (buffer) {
  12345. buffer.references--;
  12346. if (buffer.references === 0) {
  12347. this._gl.deleteBuffer(buffer);
  12348. return true;
  12349. }
  12350. return false;
  12351. };
  12352. Engine.prototype.createInstancesBuffer = function (capacity) {
  12353. var buffer = this._gl.createBuffer();
  12354. if (!buffer) {
  12355. throw new Error("Unable to create instance buffer");
  12356. }
  12357. buffer.capacity = capacity;
  12358. this.bindArrayBuffer(buffer);
  12359. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12360. return buffer;
  12361. };
  12362. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12363. this._gl.deleteBuffer(buffer);
  12364. };
  12365. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12366. this.bindArrayBuffer(instancesBuffer);
  12367. if (data) {
  12368. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12369. }
  12370. if (offsetLocations[0].index !== undefined) {
  12371. var stride = 0;
  12372. for (var i = 0; i < offsetLocations.length; i++) {
  12373. var ai = offsetLocations[i];
  12374. stride += ai.attributeSize * 4;
  12375. }
  12376. for (var i = 0; i < offsetLocations.length; i++) {
  12377. var ai = offsetLocations[i];
  12378. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12379. this._gl.enableVertexAttribArray(ai.index);
  12380. this._vertexAttribArraysEnabled[ai.index] = true;
  12381. }
  12382. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12383. this._gl.vertexAttribDivisor(ai.index, 1);
  12384. this._currentInstanceLocations.push(ai.index);
  12385. this._currentInstanceBuffers.push(instancesBuffer);
  12386. }
  12387. }
  12388. else {
  12389. for (var index = 0; index < 4; index++) {
  12390. var offsetLocation = offsetLocations[index];
  12391. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12392. this._gl.enableVertexAttribArray(offsetLocation);
  12393. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12394. }
  12395. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12396. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12397. this._currentInstanceLocations.push(offsetLocation);
  12398. this._currentInstanceBuffers.push(instancesBuffer);
  12399. }
  12400. }
  12401. };
  12402. Engine.prototype.applyStates = function () {
  12403. this._depthCullingState.apply(this._gl);
  12404. this._stencilState.apply(this._gl);
  12405. this._alphaState.apply(this._gl);
  12406. };
  12407. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12408. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12409. };
  12410. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12411. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12412. };
  12413. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12414. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12415. };
  12416. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12417. // Apply states
  12418. this.applyStates();
  12419. this._drawCalls.addCount(1, false);
  12420. // Render
  12421. var drawMode = this.DrawMode(fillMode);
  12422. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12423. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12424. if (instancesCount) {
  12425. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12426. }
  12427. else {
  12428. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12429. }
  12430. };
  12431. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12432. // Apply states
  12433. this.applyStates();
  12434. this._drawCalls.addCount(1, false);
  12435. var drawMode = this.DrawMode(fillMode);
  12436. if (instancesCount) {
  12437. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12438. }
  12439. else {
  12440. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12441. }
  12442. };
  12443. Engine.prototype.DrawMode = function (fillMode) {
  12444. switch (fillMode) {
  12445. // Triangle views
  12446. case BABYLON.Material.TriangleFillMode:
  12447. return this._gl.TRIANGLES;
  12448. case BABYLON.Material.PointFillMode:
  12449. return this._gl.POINTS;
  12450. case BABYLON.Material.WireFrameFillMode:
  12451. return this._gl.LINES;
  12452. // Draw modes
  12453. case BABYLON.Material.PointListDrawMode:
  12454. return this._gl.POINTS;
  12455. case BABYLON.Material.LineListDrawMode:
  12456. return this._gl.LINES;
  12457. case BABYLON.Material.LineLoopDrawMode:
  12458. return this._gl.LINE_LOOP;
  12459. case BABYLON.Material.LineStripDrawMode:
  12460. return this._gl.LINE_STRIP;
  12461. case BABYLON.Material.TriangleStripDrawMode:
  12462. return this._gl.TRIANGLE_STRIP;
  12463. case BABYLON.Material.TriangleFanDrawMode:
  12464. return this._gl.TRIANGLE_FAN;
  12465. default:
  12466. return this._gl.TRIANGLES;
  12467. }
  12468. };
  12469. // Shaders
  12470. Engine.prototype._releaseEffect = function (effect) {
  12471. if (this._compiledEffects[effect._key]) {
  12472. delete this._compiledEffects[effect._key];
  12473. this._deleteProgram(effect.getProgram());
  12474. }
  12475. };
  12476. Engine.prototype._deleteProgram = function (program) {
  12477. if (program) {
  12478. program.__SPECTOR_rebuildProgram = null;
  12479. if (program.transformFeedback) {
  12480. this.deleteTransformFeedback(program.transformFeedback);
  12481. program.transformFeedback = null;
  12482. }
  12483. this._gl.deleteProgram(program);
  12484. }
  12485. };
  12486. /**
  12487. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12488. * @param samplers An array of string used to represent textures
  12489. */
  12490. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12491. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12492. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12493. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12494. if (this._compiledEffects[name]) {
  12495. var compiledEffect = this._compiledEffects[name];
  12496. if (onCompiled && compiledEffect.isReady()) {
  12497. onCompiled(compiledEffect);
  12498. }
  12499. return compiledEffect;
  12500. }
  12501. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12502. effect._key = name;
  12503. this._compiledEffects[name] = effect;
  12504. return effect;
  12505. };
  12506. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12507. if (uniformsNames === void 0) { uniformsNames = []; }
  12508. if (samplers === void 0) { samplers = []; }
  12509. if (defines === void 0) { defines = ""; }
  12510. return this.createEffect({
  12511. vertex: "particles",
  12512. fragmentElement: fragmentName
  12513. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12514. };
  12515. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12516. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12517. context = context || this._gl;
  12518. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12519. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12520. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12521. };
  12522. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12523. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12524. context = context || this._gl;
  12525. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12526. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12527. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12528. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12529. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12530. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12531. return program;
  12532. };
  12533. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12534. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12535. var shaderProgram = context.createProgram();
  12536. if (!shaderProgram) {
  12537. throw new Error("Unable to create program");
  12538. }
  12539. context.attachShader(shaderProgram, vertexShader);
  12540. context.attachShader(shaderProgram, fragmentShader);
  12541. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12542. var transformFeedback = this.createTransformFeedback();
  12543. this.bindTransformFeedback(transformFeedback);
  12544. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12545. shaderProgram.transformFeedback = transformFeedback;
  12546. }
  12547. context.linkProgram(shaderProgram);
  12548. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12549. this.bindTransformFeedback(null);
  12550. }
  12551. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12552. if (!linked) {
  12553. context.validateProgram(shaderProgram);
  12554. var error = context.getProgramInfoLog(shaderProgram);
  12555. if (error) {
  12556. throw new Error(error);
  12557. }
  12558. }
  12559. context.deleteShader(vertexShader);
  12560. context.deleteShader(fragmentShader);
  12561. return shaderProgram;
  12562. };
  12563. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12564. var results = new Array();
  12565. for (var index = 0; index < uniformsNames.length; index++) {
  12566. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12567. }
  12568. return results;
  12569. };
  12570. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12571. var results = [];
  12572. for (var index = 0; index < attributesNames.length; index++) {
  12573. try {
  12574. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12575. }
  12576. catch (e) {
  12577. results.push(-1);
  12578. }
  12579. }
  12580. return results;
  12581. };
  12582. Engine.prototype.enableEffect = function (effect) {
  12583. if (!effect) {
  12584. return;
  12585. }
  12586. // Use program
  12587. this.bindSamplers(effect);
  12588. this._currentEffect = effect;
  12589. if (effect.onBind) {
  12590. effect.onBind(effect);
  12591. }
  12592. effect.onBindObservable.notifyObservers(effect);
  12593. };
  12594. Engine.prototype.setIntArray = function (uniform, array) {
  12595. if (!uniform)
  12596. return;
  12597. this._gl.uniform1iv(uniform, array);
  12598. };
  12599. Engine.prototype.setIntArray2 = function (uniform, array) {
  12600. if (!uniform || array.length % 2 !== 0)
  12601. return;
  12602. this._gl.uniform2iv(uniform, array);
  12603. };
  12604. Engine.prototype.setIntArray3 = function (uniform, array) {
  12605. if (!uniform || array.length % 3 !== 0)
  12606. return;
  12607. this._gl.uniform3iv(uniform, array);
  12608. };
  12609. Engine.prototype.setIntArray4 = function (uniform, array) {
  12610. if (!uniform || array.length % 4 !== 0)
  12611. return;
  12612. this._gl.uniform4iv(uniform, array);
  12613. };
  12614. Engine.prototype.setFloatArray = function (uniform, array) {
  12615. if (!uniform)
  12616. return;
  12617. this._gl.uniform1fv(uniform, array);
  12618. };
  12619. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12620. if (!uniform || array.length % 2 !== 0)
  12621. return;
  12622. this._gl.uniform2fv(uniform, array);
  12623. };
  12624. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12625. if (!uniform || array.length % 3 !== 0)
  12626. return;
  12627. this._gl.uniform3fv(uniform, array);
  12628. };
  12629. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12630. if (!uniform || array.length % 4 !== 0)
  12631. return;
  12632. this._gl.uniform4fv(uniform, array);
  12633. };
  12634. Engine.prototype.setArray = function (uniform, array) {
  12635. if (!uniform)
  12636. return;
  12637. this._gl.uniform1fv(uniform, array);
  12638. };
  12639. Engine.prototype.setArray2 = function (uniform, array) {
  12640. if (!uniform || array.length % 2 !== 0)
  12641. return;
  12642. this._gl.uniform2fv(uniform, array);
  12643. };
  12644. Engine.prototype.setArray3 = function (uniform, array) {
  12645. if (!uniform || array.length % 3 !== 0)
  12646. return;
  12647. this._gl.uniform3fv(uniform, array);
  12648. };
  12649. Engine.prototype.setArray4 = function (uniform, array) {
  12650. if (!uniform || array.length % 4 !== 0)
  12651. return;
  12652. this._gl.uniform4fv(uniform, array);
  12653. };
  12654. Engine.prototype.setMatrices = function (uniform, matrices) {
  12655. if (!uniform)
  12656. return;
  12657. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12658. };
  12659. Engine.prototype.setMatrix = function (uniform, matrix) {
  12660. if (!uniform)
  12661. return;
  12662. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12663. };
  12664. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12665. if (!uniform)
  12666. return;
  12667. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12668. };
  12669. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12670. if (!uniform)
  12671. return;
  12672. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12673. };
  12674. Engine.prototype.setInt = function (uniform, value) {
  12675. if (!uniform)
  12676. return;
  12677. this._gl.uniform1i(uniform, value);
  12678. };
  12679. Engine.prototype.setFloat = function (uniform, value) {
  12680. if (!uniform)
  12681. return;
  12682. this._gl.uniform1f(uniform, value);
  12683. };
  12684. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12685. if (!uniform)
  12686. return;
  12687. this._gl.uniform2f(uniform, x, y);
  12688. };
  12689. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12690. if (!uniform)
  12691. return;
  12692. this._gl.uniform3f(uniform, x, y, z);
  12693. };
  12694. Engine.prototype.setBool = function (uniform, bool) {
  12695. if (!uniform)
  12696. return;
  12697. this._gl.uniform1i(uniform, bool);
  12698. };
  12699. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12700. if (!uniform)
  12701. return;
  12702. this._gl.uniform4f(uniform, x, y, z, w);
  12703. };
  12704. Engine.prototype.setColor3 = function (uniform, color3) {
  12705. if (!uniform)
  12706. return;
  12707. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12708. };
  12709. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12710. if (!uniform)
  12711. return;
  12712. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12713. };
  12714. /**
  12715. * Sets a Color4 on a uniform variable
  12716. * @param uniform defines the uniform location
  12717. * @param color4 defines the value to be set
  12718. */
  12719. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12720. if (!uniform)
  12721. return;
  12722. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12723. };
  12724. // States
  12725. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12726. if (zOffset === void 0) { zOffset = 0; }
  12727. if (reverseSide === void 0) { reverseSide = false; }
  12728. // Culling
  12729. if (this._depthCullingState.cull !== culling || force) {
  12730. this._depthCullingState.cull = culling;
  12731. }
  12732. // Cull face
  12733. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12734. if (this._depthCullingState.cullFace !== cullFace || force) {
  12735. this._depthCullingState.cullFace = cullFace;
  12736. }
  12737. // Z offset
  12738. this.setZOffset(zOffset);
  12739. // Front face
  12740. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12741. if (this._depthCullingState.frontFace !== frontFace || force) {
  12742. this._depthCullingState.frontFace = frontFace;
  12743. }
  12744. };
  12745. Engine.prototype.setZOffset = function (value) {
  12746. this._depthCullingState.zOffset = value;
  12747. };
  12748. Engine.prototype.getZOffset = function () {
  12749. return this._depthCullingState.zOffset;
  12750. };
  12751. Engine.prototype.setDepthBuffer = function (enable) {
  12752. this._depthCullingState.depthTest = enable;
  12753. };
  12754. Engine.prototype.getDepthWrite = function () {
  12755. return this._depthCullingState.depthMask;
  12756. };
  12757. Engine.prototype.setDepthWrite = function (enable) {
  12758. this._depthCullingState.depthMask = enable;
  12759. };
  12760. Engine.prototype.setColorWrite = function (enable) {
  12761. this._gl.colorMask(enable, enable, enable, enable);
  12762. this._colorWrite = enable;
  12763. };
  12764. Engine.prototype.getColorWrite = function () {
  12765. return this._colorWrite;
  12766. };
  12767. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12768. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12769. };
  12770. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12771. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12772. if (this._alphaMode === mode) {
  12773. return;
  12774. }
  12775. switch (mode) {
  12776. case Engine.ALPHA_DISABLE:
  12777. this._alphaState.alphaBlend = false;
  12778. break;
  12779. case Engine.ALPHA_PREMULTIPLIED:
  12780. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12781. this._alphaState.alphaBlend = true;
  12782. break;
  12783. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12784. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12785. this._alphaState.alphaBlend = true;
  12786. break;
  12787. case Engine.ALPHA_COMBINE:
  12788. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12789. this._alphaState.alphaBlend = true;
  12790. break;
  12791. case Engine.ALPHA_ONEONE:
  12792. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12793. this._alphaState.alphaBlend = true;
  12794. break;
  12795. case Engine.ALPHA_ADD:
  12796. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12797. this._alphaState.alphaBlend = true;
  12798. break;
  12799. case Engine.ALPHA_SUBTRACT:
  12800. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12801. this._alphaState.alphaBlend = true;
  12802. break;
  12803. case Engine.ALPHA_MULTIPLY:
  12804. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12805. this._alphaState.alphaBlend = true;
  12806. break;
  12807. case Engine.ALPHA_MAXIMIZED:
  12808. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12809. this._alphaState.alphaBlend = true;
  12810. break;
  12811. case Engine.ALPHA_INTERPOLATE:
  12812. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12813. this._alphaState.alphaBlend = true;
  12814. break;
  12815. case Engine.ALPHA_SCREENMODE:
  12816. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12817. this._alphaState.alphaBlend = true;
  12818. break;
  12819. }
  12820. if (!noDepthWriteChange) {
  12821. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12822. }
  12823. this._alphaMode = mode;
  12824. };
  12825. Engine.prototype.getAlphaMode = function () {
  12826. return this._alphaMode;
  12827. };
  12828. // Textures
  12829. Engine.prototype.wipeCaches = function (bruteForce) {
  12830. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12831. return;
  12832. }
  12833. this._currentEffect = null;
  12834. // 6/8/2017: deltakosh: Should not be required anymore.
  12835. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12836. if (bruteForce) {
  12837. this.resetTextureCache();
  12838. this._currentProgram = null;
  12839. this._stencilState.reset();
  12840. this._depthCullingState.reset();
  12841. this.setDepthFunctionToLessOrEqual();
  12842. this._alphaState.reset();
  12843. }
  12844. this._resetVertexBufferBinding();
  12845. this._cachedIndexBuffer = null;
  12846. this._cachedEffectForVertexBuffers = null;
  12847. this._unbindVertexArrayObject();
  12848. this.bindIndexBuffer(null);
  12849. };
  12850. /**
  12851. * Set the compressed texture format to use, based on the formats you have, and the formats
  12852. * supported by the hardware / browser.
  12853. *
  12854. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12855. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12856. * to API arguments needed to compressed textures. This puts the burden on the container
  12857. * generator to house the arcane code for determining these for current & future formats.
  12858. *
  12859. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12860. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12861. *
  12862. * Note: The result of this call is not taken into account when a texture is base64.
  12863. *
  12864. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12865. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12866. *
  12867. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12868. * @returns The extension selected.
  12869. */
  12870. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12871. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12872. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12873. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12874. return this._textureFormatInUse = this._texturesSupported[i];
  12875. }
  12876. }
  12877. }
  12878. // actively set format to nothing, to allow this to be called more than once
  12879. // and possibly fail the 2nd time
  12880. this._textureFormatInUse = null;
  12881. return null;
  12882. };
  12883. Engine.prototype._createTexture = function () {
  12884. var texture = this._gl.createTexture();
  12885. if (!texture) {
  12886. throw new Error("Unable to create texture");
  12887. }
  12888. return texture;
  12889. };
  12890. /**
  12891. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12892. * @param {string} urlArg- This contains one of the following:
  12893. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12894. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12895. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12896. *
  12897. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12898. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12899. * @param {Scene} scene- Needed for loading to the correct scene.
  12900. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12901. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12902. * @param {callback} onError- Optional callback to be called upon failure.
  12903. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12904. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12905. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12906. *
  12907. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12908. */
  12909. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12910. var _this = this;
  12911. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12912. if (onLoad === void 0) { onLoad = null; }
  12913. if (onError === void 0) { onError = null; }
  12914. if (buffer === void 0) { buffer = null; }
  12915. if (fallBack === void 0) { fallBack = null; }
  12916. if (format === void 0) { format = null; }
  12917. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12918. var fromData = url.substr(0, 5) === "data:";
  12919. var fromBlob = url.substr(0, 5) === "blob:";
  12920. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12921. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12922. // establish the file extension, if possible
  12923. var lastDot = url.lastIndexOf('.');
  12924. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12925. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12926. var isTGA = (extension.indexOf(".tga") === 0);
  12927. // determine if a ktx file should be substituted
  12928. var isKTX = false;
  12929. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12930. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12931. isKTX = true;
  12932. }
  12933. if (scene) {
  12934. scene._addPendingData(texture);
  12935. }
  12936. texture.url = url;
  12937. texture.generateMipMaps = !noMipmap;
  12938. texture.samplingMode = samplingMode;
  12939. texture.invertY = invertY;
  12940. if (!this._doNotHandleContextLost) {
  12941. // Keep a link to the buffer only if we plan to handle context lost
  12942. texture._buffer = buffer;
  12943. }
  12944. var onLoadObserver = null;
  12945. if (onLoad && !fallBack) {
  12946. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12947. }
  12948. if (!fallBack)
  12949. this._internalTexturesCache.push(texture);
  12950. var onerror = function (message, exception) {
  12951. if (scene) {
  12952. scene._removePendingData(texture);
  12953. }
  12954. if (onLoadObserver) {
  12955. texture.onLoadedObservable.remove(onLoadObserver);
  12956. }
  12957. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12958. if (isKTX) {
  12959. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12960. }
  12961. else if (BABYLON.Tools.UseFallbackTexture) {
  12962. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12963. }
  12964. if (onError) {
  12965. onError(message || "Unknown error", exception);
  12966. }
  12967. };
  12968. var callback = null;
  12969. // processing for non-image formats
  12970. if (isKTX || isTGA || isDDS) {
  12971. if (isKTX) {
  12972. callback = function (data) {
  12973. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12974. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12975. ktx.uploadLevels(_this._gl, !noMipmap);
  12976. return false;
  12977. }, samplingMode);
  12978. };
  12979. }
  12980. else if (isTGA) {
  12981. callback = function (arrayBuffer) {
  12982. var data = new Uint8Array(arrayBuffer);
  12983. var header = BABYLON.TGATools.GetTGAHeader(data);
  12984. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12985. BABYLON.TGATools.UploadContent(_this._gl, data);
  12986. return false;
  12987. }, samplingMode);
  12988. };
  12989. }
  12990. else if (isDDS) {
  12991. callback = function (data) {
  12992. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12993. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12994. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12995. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12996. return false;
  12997. }, samplingMode);
  12998. };
  12999. }
  13000. if (!buffer) {
  13001. this._loadFile(url, function (data) {
  13002. if (callback) {
  13003. callback(data);
  13004. }
  13005. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13006. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13007. });
  13008. }
  13009. else {
  13010. if (callback) {
  13011. callback(buffer);
  13012. }
  13013. }
  13014. // image format processing
  13015. }
  13016. else {
  13017. var onload = function (img) {
  13018. if (fromBlob && !_this._doNotHandleContextLost) {
  13019. // We need to store the image if we need to rebuild the texture
  13020. // in case of a webgl context lost
  13021. texture._buffer = img;
  13022. }
  13023. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13024. var gl = _this._gl;
  13025. var isPot = (img.width === potWidth && img.height === potHeight);
  13026. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13027. if (isPot) {
  13028. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13029. return false;
  13030. }
  13031. // Using shaders to rescale because canvas.drawImage is lossy
  13032. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13033. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13034. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13035. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13036. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13037. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13038. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13039. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13040. _this._releaseTexture(source);
  13041. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13042. continuationCallback();
  13043. });
  13044. return true;
  13045. }, samplingMode);
  13046. };
  13047. if (!fromData || isBase64)
  13048. if (buffer instanceof HTMLImageElement) {
  13049. onload(buffer);
  13050. }
  13051. else {
  13052. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13053. }
  13054. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13055. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13056. else
  13057. onload(buffer);
  13058. }
  13059. return texture;
  13060. };
  13061. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13062. var _this = this;
  13063. var rtt = this.createRenderTargetTexture({
  13064. width: destination.width,
  13065. height: destination.height,
  13066. }, {
  13067. generateMipMaps: false,
  13068. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13069. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13070. generateDepthBuffer: false,
  13071. generateStencilBuffer: false
  13072. });
  13073. if (!this._rescalePostProcess) {
  13074. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13075. }
  13076. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13077. _this._rescalePostProcess.onApply = function (effect) {
  13078. effect._bindTexture("textureSampler", source);
  13079. };
  13080. var hostingScene = scene;
  13081. if (!hostingScene) {
  13082. hostingScene = _this.scenes[_this.scenes.length - 1];
  13083. }
  13084. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13085. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13086. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13087. _this.unBindFramebuffer(rtt);
  13088. _this._releaseTexture(rtt);
  13089. if (onComplete) {
  13090. onComplete();
  13091. }
  13092. });
  13093. };
  13094. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13095. if (compression === void 0) { compression = null; }
  13096. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13097. if (!texture) {
  13098. return;
  13099. }
  13100. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13101. var internalFormat = this._getInternalFormat(format);
  13102. var textureType = this._getWebGLTextureType(type);
  13103. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13104. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13105. if (!this._doNotHandleContextLost) {
  13106. texture._bufferView = data;
  13107. texture.format = format;
  13108. texture.type = type;
  13109. texture.invertY = invertY;
  13110. texture._compression = compression;
  13111. }
  13112. if (texture.width % 4 !== 0) {
  13113. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13114. }
  13115. if (compression && data) {
  13116. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13117. }
  13118. else {
  13119. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13120. }
  13121. if (texture.generateMipMaps) {
  13122. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13123. }
  13124. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13125. // this.resetTextureCache();
  13126. texture.isReady = true;
  13127. };
  13128. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13129. if (compression === void 0) { compression = null; }
  13130. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13131. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13132. texture.baseWidth = width;
  13133. texture.baseHeight = height;
  13134. texture.width = width;
  13135. texture.height = height;
  13136. texture.format = format;
  13137. texture.generateMipMaps = generateMipMaps;
  13138. texture.samplingMode = samplingMode;
  13139. texture.invertY = invertY;
  13140. texture._compression = compression;
  13141. texture.type = type;
  13142. if (!this._doNotHandleContextLost) {
  13143. texture._bufferView = data;
  13144. }
  13145. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13146. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13147. // Filters
  13148. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13149. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13150. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13151. if (generateMipMaps) {
  13152. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13153. }
  13154. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13155. this._internalTexturesCache.push(texture);
  13156. return texture;
  13157. };
  13158. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13159. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13160. texture.baseWidth = width;
  13161. texture.baseHeight = height;
  13162. if (generateMipMaps) {
  13163. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13164. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13165. }
  13166. // this.resetTextureCache();
  13167. texture.width = width;
  13168. texture.height = height;
  13169. texture.isReady = false;
  13170. texture.generateMipMaps = generateMipMaps;
  13171. texture.samplingMode = samplingMode;
  13172. this.updateTextureSamplingMode(samplingMode, texture);
  13173. this._internalTexturesCache.push(texture);
  13174. return texture;
  13175. };
  13176. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13177. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13178. if (texture.isCube) {
  13179. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13180. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13181. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13182. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13183. }
  13184. else if (texture.is3D) {
  13185. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13186. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13187. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13188. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13189. }
  13190. else {
  13191. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13192. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13193. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13194. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13195. }
  13196. texture.samplingMode = samplingMode;
  13197. };
  13198. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13199. if (premulAlpha === void 0) { premulAlpha = false; }
  13200. if (!texture) {
  13201. return;
  13202. }
  13203. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13204. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13205. if (premulAlpha) {
  13206. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13207. }
  13208. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13209. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13210. if (texture.generateMipMaps) {
  13211. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13212. }
  13213. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13214. if (premulAlpha) {
  13215. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13216. }
  13217. texture.isReady = true;
  13218. };
  13219. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13220. if (!texture || texture._isDisabled) {
  13221. return;
  13222. }
  13223. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13224. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13225. try {
  13226. // Testing video texture support
  13227. if (this._videoTextureSupported === undefined) {
  13228. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13229. if (this._gl.getError() !== 0) {
  13230. this._videoTextureSupported = false;
  13231. }
  13232. else {
  13233. this._videoTextureSupported = true;
  13234. }
  13235. }
  13236. // Copy video through the current working canvas if video texture is not supported
  13237. if (!this._videoTextureSupported) {
  13238. if (!texture._workingCanvas) {
  13239. texture._workingCanvas = document.createElement("canvas");
  13240. var context = texture._workingCanvas.getContext("2d");
  13241. if (!context) {
  13242. throw new Error("Unable to get 2d context");
  13243. }
  13244. texture._workingContext = context;
  13245. texture._workingCanvas.width = texture.width;
  13246. texture._workingCanvas.height = texture.height;
  13247. }
  13248. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13249. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13250. }
  13251. else {
  13252. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13253. }
  13254. if (texture.generateMipMaps) {
  13255. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13256. }
  13257. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13258. // this.resetTextureCache();
  13259. texture.isReady = true;
  13260. }
  13261. catch (ex) {
  13262. // Something unexpected
  13263. // Let's disable the texture
  13264. texture._isDisabled = true;
  13265. }
  13266. };
  13267. /**
  13268. * Updates a depth texture Comparison Mode and Function.
  13269. * If the comparison Function is equal to 0, the mode will be set to none.
  13270. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13271. * @param texture The texture to set the comparison function for
  13272. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13273. */
  13274. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13275. if (this.webGLVersion === 1) {
  13276. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13277. return;
  13278. }
  13279. var gl = this._gl;
  13280. if (texture.isCube) {
  13281. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13282. if (comparisonFunction === 0) {
  13283. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13284. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13285. }
  13286. else {
  13287. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13288. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13289. }
  13290. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13291. }
  13292. else {
  13293. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13294. if (comparisonFunction === 0) {
  13295. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13296. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13297. }
  13298. else {
  13299. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13300. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13301. }
  13302. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13303. }
  13304. texture._comparisonFunction = comparisonFunction;
  13305. };
  13306. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13307. var width = size.width || size;
  13308. var height = size.height || size;
  13309. internalTexture.baseWidth = width;
  13310. internalTexture.baseHeight = height;
  13311. internalTexture.width = width;
  13312. internalTexture.height = height;
  13313. internalTexture.isReady = true;
  13314. internalTexture.samples = 1;
  13315. internalTexture.generateMipMaps = false;
  13316. internalTexture._generateDepthBuffer = true;
  13317. internalTexture._generateStencilBuffer = generateStencil;
  13318. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13319. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13320. internalTexture._comparisonFunction = comparisonFunction;
  13321. var gl = this._gl;
  13322. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13323. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13324. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13325. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13326. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13327. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13328. if (comparisonFunction === 0) {
  13329. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13330. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13331. }
  13332. else {
  13333. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13334. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13335. }
  13336. };
  13337. /**
  13338. * Creates a depth stencil texture.
  13339. * This is only available in WebGL 2 or with the depth texture extension available.
  13340. * @param size The size of face edge in the texture.
  13341. * @param options The options defining the texture.
  13342. * @returns The texture
  13343. */
  13344. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13345. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13346. if (!this._caps.depthTextureExtension) {
  13347. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13348. return internalTexture;
  13349. }
  13350. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13351. var gl = this._gl;
  13352. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13353. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13354. if (this.webGLVersion > 1) {
  13355. if (internalOptions.generateStencil) {
  13356. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13357. }
  13358. else {
  13359. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13360. }
  13361. }
  13362. else {
  13363. if (internalOptions.generateStencil) {
  13364. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13365. }
  13366. else {
  13367. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13368. }
  13369. }
  13370. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13371. return internalTexture;
  13372. };
  13373. /**
  13374. * Creates a depth stencil cube texture.
  13375. * This is only available in WebGL 2.
  13376. * @param size The size of face edge in the cube texture.
  13377. * @param options The options defining the cube texture.
  13378. * @returns The cube texture
  13379. */
  13380. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13381. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13382. internalTexture.isCube = true;
  13383. if (this.webGLVersion === 1) {
  13384. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13385. return internalTexture;
  13386. }
  13387. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13388. var gl = this._gl;
  13389. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13390. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13391. // Create the depth/stencil buffer
  13392. for (var face = 0; face < 6; face++) {
  13393. if (internalOptions.generateStencil) {
  13394. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13395. }
  13396. else {
  13397. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13398. }
  13399. }
  13400. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13401. return internalTexture;
  13402. };
  13403. /**
  13404. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13405. * @param renderTarget The render target to set the frame buffer for
  13406. */
  13407. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13408. // Create the framebuffer
  13409. var internalTexture = renderTarget.getInternalTexture();
  13410. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13411. return;
  13412. }
  13413. var gl = this._gl;
  13414. var depthStencilTexture = renderTarget.depthStencilTexture;
  13415. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13416. if (depthStencilTexture.isCube) {
  13417. if (depthStencilTexture._generateStencilBuffer) {
  13418. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13419. }
  13420. else {
  13421. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13422. }
  13423. }
  13424. else {
  13425. if (depthStencilTexture._generateStencilBuffer) {
  13426. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13427. }
  13428. else {
  13429. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13430. }
  13431. }
  13432. this.bindUnboundFramebuffer(null);
  13433. };
  13434. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13435. var fullOptions = new RenderTargetCreationOptions();
  13436. if (options !== undefined && typeof options === "object") {
  13437. fullOptions.generateMipMaps = options.generateMipMaps;
  13438. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13439. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13440. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13441. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13442. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13443. }
  13444. else {
  13445. fullOptions.generateMipMaps = options;
  13446. fullOptions.generateDepthBuffer = true;
  13447. fullOptions.generateStencilBuffer = false;
  13448. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13449. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13450. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13451. }
  13452. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13453. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13454. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13455. }
  13456. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13457. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13458. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13459. }
  13460. var gl = this._gl;
  13461. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13462. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13463. var width = size.width || size;
  13464. var height = size.height || size;
  13465. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13466. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13467. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13468. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13469. }
  13470. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13471. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13472. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13473. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13474. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13475. // Create the framebuffer
  13476. var framebuffer = gl.createFramebuffer();
  13477. this.bindUnboundFramebuffer(framebuffer);
  13478. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13479. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13480. if (fullOptions.generateMipMaps) {
  13481. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13482. }
  13483. // Unbind
  13484. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13485. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13486. this.bindUnboundFramebuffer(null);
  13487. texture._framebuffer = framebuffer;
  13488. texture.baseWidth = width;
  13489. texture.baseHeight = height;
  13490. texture.width = width;
  13491. texture.height = height;
  13492. texture.isReady = true;
  13493. texture.samples = 1;
  13494. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13495. texture.samplingMode = fullOptions.samplingMode;
  13496. texture.type = fullOptions.type;
  13497. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13498. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13499. // this.resetTextureCache();
  13500. this._internalTexturesCache.push(texture);
  13501. return texture;
  13502. };
  13503. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13504. var generateMipMaps = false;
  13505. var generateDepthBuffer = true;
  13506. var generateStencilBuffer = false;
  13507. var generateDepthTexture = false;
  13508. var textureCount = 1;
  13509. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13510. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13511. var types = [], samplingModes = [];
  13512. if (options !== undefined) {
  13513. generateMipMaps = options.generateMipMaps;
  13514. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13515. generateStencilBuffer = options.generateStencilBuffer;
  13516. generateDepthTexture = options.generateDepthTexture;
  13517. textureCount = options.textureCount || 1;
  13518. if (options.types) {
  13519. types = options.types;
  13520. }
  13521. if (options.samplingModes) {
  13522. samplingModes = options.samplingModes;
  13523. }
  13524. }
  13525. var gl = this._gl;
  13526. // Create the framebuffer
  13527. var framebuffer = gl.createFramebuffer();
  13528. this.bindUnboundFramebuffer(framebuffer);
  13529. var width = size.width || size;
  13530. var height = size.height || size;
  13531. var textures = [];
  13532. var attachments = [];
  13533. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13534. for (var i = 0; i < textureCount; i++) {
  13535. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13536. var type = types[i] || defaultType;
  13537. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13538. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13539. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13540. }
  13541. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13542. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13543. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13544. }
  13545. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13546. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13547. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13548. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13549. }
  13550. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13551. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13552. textures.push(texture);
  13553. attachments.push(attachment);
  13554. gl.activeTexture(gl["TEXTURE" + i]);
  13555. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13556. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13557. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13558. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13559. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13560. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13561. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13562. if (generateMipMaps) {
  13563. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13564. }
  13565. // Unbind
  13566. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13567. texture._framebuffer = framebuffer;
  13568. texture._depthStencilBuffer = depthStencilBuffer;
  13569. texture.baseWidth = width;
  13570. texture.baseHeight = height;
  13571. texture.width = width;
  13572. texture.height = height;
  13573. texture.isReady = true;
  13574. texture.samples = 1;
  13575. texture.generateMipMaps = generateMipMaps;
  13576. texture.samplingMode = samplingMode;
  13577. texture.type = type;
  13578. texture._generateDepthBuffer = generateDepthBuffer;
  13579. texture._generateStencilBuffer = generateStencilBuffer;
  13580. texture._attachments = attachments;
  13581. this._internalTexturesCache.push(texture);
  13582. }
  13583. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13584. // Depth texture
  13585. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13586. gl.activeTexture(gl.TEXTURE0);
  13587. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13588. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13589. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13590. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13591. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13592. 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);
  13593. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13594. depthTexture._framebuffer = framebuffer;
  13595. depthTexture.baseWidth = width;
  13596. depthTexture.baseHeight = height;
  13597. depthTexture.width = width;
  13598. depthTexture.height = height;
  13599. depthTexture.isReady = true;
  13600. depthTexture.samples = 1;
  13601. depthTexture.generateMipMaps = generateMipMaps;
  13602. depthTexture.samplingMode = gl.NEAREST;
  13603. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13604. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13605. textures.push(depthTexture);
  13606. this._internalTexturesCache.push(depthTexture);
  13607. }
  13608. gl.drawBuffers(attachments);
  13609. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13610. this.bindUnboundFramebuffer(null);
  13611. this.resetTextureCache();
  13612. return textures;
  13613. };
  13614. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13615. if (samples === void 0) { samples = 1; }
  13616. var depthStencilBuffer = null;
  13617. var gl = this._gl;
  13618. // Create the depth/stencil buffer
  13619. if (generateStencilBuffer) {
  13620. depthStencilBuffer = gl.createRenderbuffer();
  13621. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13622. if (samples > 1) {
  13623. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13624. }
  13625. else {
  13626. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13627. }
  13628. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13629. }
  13630. else if (generateDepthBuffer) {
  13631. depthStencilBuffer = gl.createRenderbuffer();
  13632. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13633. if (samples > 1) {
  13634. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13635. }
  13636. else {
  13637. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13638. }
  13639. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13640. }
  13641. return depthStencilBuffer;
  13642. };
  13643. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13644. if (this.webGLVersion < 2 || !texture) {
  13645. return 1;
  13646. }
  13647. if (texture.samples === samples) {
  13648. return samples;
  13649. }
  13650. var gl = this._gl;
  13651. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13652. // Dispose previous render buffers
  13653. if (texture._depthStencilBuffer) {
  13654. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13655. texture._depthStencilBuffer = null;
  13656. }
  13657. if (texture._MSAAFramebuffer) {
  13658. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13659. texture._MSAAFramebuffer = null;
  13660. }
  13661. if (texture._MSAARenderBuffer) {
  13662. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13663. texture._MSAARenderBuffer = null;
  13664. }
  13665. if (samples > 1) {
  13666. var framebuffer = gl.createFramebuffer();
  13667. if (!framebuffer) {
  13668. throw new Error("Unable to create multi sampled framebuffer");
  13669. }
  13670. texture._MSAAFramebuffer = framebuffer;
  13671. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13672. var colorRenderbuffer = gl.createRenderbuffer();
  13673. if (!colorRenderbuffer) {
  13674. throw new Error("Unable to create multi sampled framebuffer");
  13675. }
  13676. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13677. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13678. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13679. texture._MSAARenderBuffer = colorRenderbuffer;
  13680. }
  13681. else {
  13682. this.bindUnboundFramebuffer(texture._framebuffer);
  13683. }
  13684. texture.samples = samples;
  13685. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13686. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13687. this.bindUnboundFramebuffer(null);
  13688. return samples;
  13689. };
  13690. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13691. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13692. return 1;
  13693. }
  13694. if (textures[0].samples === samples) {
  13695. return samples;
  13696. }
  13697. var gl = this._gl;
  13698. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13699. // Dispose previous render buffers
  13700. if (textures[0]._depthStencilBuffer) {
  13701. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13702. textures[0]._depthStencilBuffer = null;
  13703. }
  13704. if (textures[0]._MSAAFramebuffer) {
  13705. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13706. textures[0]._MSAAFramebuffer = null;
  13707. }
  13708. for (var i = 0; i < textures.length; i++) {
  13709. if (textures[i]._MSAARenderBuffer) {
  13710. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13711. textures[i]._MSAARenderBuffer = null;
  13712. }
  13713. }
  13714. if (samples > 1) {
  13715. var framebuffer = gl.createFramebuffer();
  13716. if (!framebuffer) {
  13717. throw new Error("Unable to create multi sampled framebuffer");
  13718. }
  13719. this.bindUnboundFramebuffer(framebuffer);
  13720. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13721. var attachments = [];
  13722. for (var i = 0; i < textures.length; i++) {
  13723. var texture = textures[i];
  13724. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13725. var colorRenderbuffer = gl.createRenderbuffer();
  13726. if (!colorRenderbuffer) {
  13727. throw new Error("Unable to create multi sampled framebuffer");
  13728. }
  13729. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13730. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13731. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13732. texture._MSAAFramebuffer = framebuffer;
  13733. texture._MSAARenderBuffer = colorRenderbuffer;
  13734. texture.samples = samples;
  13735. texture._depthStencilBuffer = depthStencilBuffer;
  13736. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13737. attachments.push(attachment);
  13738. }
  13739. gl.drawBuffers(attachments);
  13740. }
  13741. else {
  13742. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13743. }
  13744. this.bindUnboundFramebuffer(null);
  13745. return samples;
  13746. };
  13747. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13748. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13749. };
  13750. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13751. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13752. };
  13753. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13754. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13755. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13756. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13757. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13758. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13759. }
  13760. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13761. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13762. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13763. }
  13764. var gl = this._gl;
  13765. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13766. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13767. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13768. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13769. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13770. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13771. }
  13772. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13774. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13775. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13776. for (var face = 0; face < 6; face++) {
  13777. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13778. }
  13779. // Create the framebuffer
  13780. var framebuffer = gl.createFramebuffer();
  13781. this.bindUnboundFramebuffer(framebuffer);
  13782. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13783. // MipMaps
  13784. if (fullOptions.generateMipMaps) {
  13785. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13786. }
  13787. // Unbind
  13788. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13789. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13790. this.bindUnboundFramebuffer(null);
  13791. texture._framebuffer = framebuffer;
  13792. texture.width = size;
  13793. texture.height = size;
  13794. texture.isReady = true;
  13795. texture.isCube = true;
  13796. texture.samples = 1;
  13797. texture.generateMipMaps = fullOptions.generateMipMaps;
  13798. texture.samplingMode = fullOptions.samplingMode;
  13799. texture.type = fullOptions.type;
  13800. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13801. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13802. this._internalTexturesCache.push(texture);
  13803. return texture;
  13804. };
  13805. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13806. var _this = this;
  13807. if (onLoad === void 0) { onLoad = null; }
  13808. if (onError === void 0) { onError = null; }
  13809. if (forcedExtension === void 0) { forcedExtension = null; }
  13810. var callback = function (loadData) {
  13811. if (!loadData) {
  13812. if (onLoad) {
  13813. onLoad(null);
  13814. }
  13815. return;
  13816. }
  13817. var texture = loadData.texture;
  13818. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13819. texture._lodGenerationScale = scale;
  13820. texture._lodGenerationOffset = offset;
  13821. if (_this._caps.textureLOD) {
  13822. // Do not add extra process if texture lod is supported.
  13823. if (onLoad) {
  13824. onLoad(texture);
  13825. }
  13826. return;
  13827. }
  13828. var mipSlices = 3;
  13829. var gl = _this._gl;
  13830. var width = loadData.width;
  13831. if (!width) {
  13832. return;
  13833. }
  13834. var textures = [];
  13835. for (var i = 0; i < mipSlices; i++) {
  13836. //compute LOD from even spacing in smoothness (matching shader calculation)
  13837. var smoothness = i / (mipSlices - 1);
  13838. var roughness = 1 - smoothness;
  13839. var minLODIndex = offset; // roughness = 0
  13840. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13841. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13842. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13843. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13844. glTextureFromLod.isCube = true;
  13845. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13846. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13847. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13848. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13849. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13850. if (loadData.isDDS) {
  13851. var info = loadData.info;
  13852. var data = loadData.data;
  13853. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13854. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13855. }
  13856. else {
  13857. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13858. }
  13859. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13860. // Wrap in a base texture for easy binding.
  13861. var lodTexture = new BABYLON.BaseTexture(scene);
  13862. lodTexture.isCube = true;
  13863. lodTexture._texture = glTextureFromLod;
  13864. glTextureFromLod.isReady = true;
  13865. textures.push(lodTexture);
  13866. }
  13867. texture._lodTextureHigh = textures[2];
  13868. texture._lodTextureMid = textures[1];
  13869. texture._lodTextureLow = textures[0];
  13870. if (onLoad) {
  13871. onLoad(texture);
  13872. }
  13873. };
  13874. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13875. };
  13876. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13877. var _this = this;
  13878. if (onLoad === void 0) { onLoad = null; }
  13879. if (onError === void 0) { onError = null; }
  13880. if (forcedExtension === void 0) { forcedExtension = null; }
  13881. var gl = this._gl;
  13882. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13883. texture.isCube = true;
  13884. texture.url = rootUrl;
  13885. texture.generateMipMaps = !noMipmap;
  13886. if (!this._doNotHandleContextLost) {
  13887. texture._extension = forcedExtension;
  13888. texture._files = files;
  13889. }
  13890. var isKTX = false;
  13891. var isDDS = false;
  13892. var lastDot = rootUrl.lastIndexOf('.');
  13893. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13894. if (this._textureFormatInUse) {
  13895. extension = this._textureFormatInUse;
  13896. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13897. isKTX = true;
  13898. }
  13899. else {
  13900. isDDS = (extension === ".dds");
  13901. }
  13902. var onerror = function (request, exception) {
  13903. if (onError && request) {
  13904. onError(request.status + " " + request.statusText, exception);
  13905. }
  13906. };
  13907. if (isKTX) {
  13908. this._loadFile(rootUrl, function (data) {
  13909. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13910. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13911. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13912. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13913. ktx.uploadLevels(_this._gl, !noMipmap);
  13914. _this.setCubeMapTextureParams(gl, loadMipmap);
  13915. texture.width = ktx.pixelWidth;
  13916. texture.height = ktx.pixelHeight;
  13917. texture.isReady = true;
  13918. }, undefined, undefined, true, onerror);
  13919. }
  13920. else if (isDDS) {
  13921. if (files && files.length === 6) {
  13922. this._cascadeLoadFiles(scene, function (imgs) {
  13923. var info;
  13924. var loadMipmap = false;
  13925. var width = 0;
  13926. for (var index = 0; index < imgs.length; index++) {
  13927. var data = imgs[index];
  13928. info = BABYLON.DDSTools.GetDDSInfo(data);
  13929. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13930. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13931. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13932. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13933. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13934. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13935. }
  13936. texture.width = info.width;
  13937. texture.height = info.height;
  13938. texture.type = info.textureType;
  13939. width = info.width;
  13940. }
  13941. _this.setCubeMapTextureParams(gl, loadMipmap);
  13942. texture.isReady = true;
  13943. if (onLoad) {
  13944. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13945. }
  13946. }, files, onError);
  13947. }
  13948. else {
  13949. this._loadFile(rootUrl, function (data) {
  13950. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13951. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13952. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13953. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13954. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13955. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13956. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13957. }
  13958. _this.setCubeMapTextureParams(gl, loadMipmap);
  13959. texture.width = info.width;
  13960. texture.height = info.height;
  13961. texture.isReady = true;
  13962. texture.type = info.textureType;
  13963. if (onLoad) {
  13964. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13965. }
  13966. }, undefined, undefined, true, onerror);
  13967. }
  13968. }
  13969. else {
  13970. if (!files) {
  13971. throw new Error("Cannot load cubemap because files were not defined");
  13972. }
  13973. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13974. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13975. var height = width;
  13976. _this._prepareWorkingCanvas();
  13977. if (!_this._workingCanvas || !_this._workingContext) {
  13978. return;
  13979. }
  13980. _this._workingCanvas.width = width;
  13981. _this._workingCanvas.height = height;
  13982. var faces = [
  13983. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13984. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13985. ];
  13986. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13987. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13988. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13989. for (var index = 0; index < faces.length; index++) {
  13990. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13991. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13992. }
  13993. if (!noMipmap) {
  13994. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13995. }
  13996. _this.setCubeMapTextureParams(gl, !noMipmap);
  13997. texture.width = width;
  13998. texture.height = height;
  13999. texture.isReady = true;
  14000. if (format) {
  14001. texture.format = format;
  14002. }
  14003. texture.onLoadedObservable.notifyObservers(texture);
  14004. texture.onLoadedObservable.clear();
  14005. if (onLoad) {
  14006. onLoad();
  14007. }
  14008. }, files, onError);
  14009. }
  14010. this._internalTexturesCache.push(texture);
  14011. return texture;
  14012. };
  14013. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14014. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14015. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14016. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14017. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14018. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14019. // this.resetTextureCache();
  14020. };
  14021. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14022. if (compression === void 0) { compression = null; }
  14023. if (level === void 0) { level = 0; }
  14024. texture._bufferViewArray = data;
  14025. texture.format = format;
  14026. texture.type = type;
  14027. texture.invertY = invertY;
  14028. texture._compression = compression;
  14029. var gl = this._gl;
  14030. var textureType = this._getWebGLTextureType(type);
  14031. var internalFormat = this._getInternalFormat(format);
  14032. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14033. var needConversion = false;
  14034. if (internalFormat === gl.RGB) {
  14035. internalFormat = gl.RGBA;
  14036. needConversion = true;
  14037. }
  14038. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14039. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14040. if (texture.width % 4 !== 0) {
  14041. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14042. }
  14043. // Data are known to be in +X +Y +Z -X -Y -Z
  14044. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14045. var faceData = data[faceIndex];
  14046. if (compression) {
  14047. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14048. }
  14049. else {
  14050. if (needConversion) {
  14051. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14052. }
  14053. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14054. }
  14055. }
  14056. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14057. if (isPot && texture.generateMipMaps && level === 0) {
  14058. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14059. }
  14060. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14061. // this.resetTextureCache();
  14062. texture.isReady = true;
  14063. };
  14064. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14065. if (compression === void 0) { compression = null; }
  14066. var gl = this._gl;
  14067. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14068. texture.isCube = true;
  14069. texture.generateMipMaps = generateMipMaps;
  14070. texture.format = format;
  14071. texture.type = type;
  14072. if (!this._doNotHandleContextLost) {
  14073. texture._bufferViewArray = data;
  14074. }
  14075. var textureType = this._getWebGLTextureType(type);
  14076. var internalFormat = this._getInternalFormat(format);
  14077. if (internalFormat === gl.RGB) {
  14078. internalFormat = gl.RGBA;
  14079. }
  14080. var width = size;
  14081. var height = width;
  14082. texture.width = width;
  14083. texture.height = height;
  14084. // Double check on POT to generate Mips.
  14085. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14086. if (!isPot) {
  14087. generateMipMaps = false;
  14088. }
  14089. // Upload data if needed. The texture won't be ready until then.
  14090. if (data) {
  14091. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14092. }
  14093. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14094. // Filters
  14095. if (data && generateMipMaps) {
  14096. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14097. }
  14098. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14099. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14100. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14101. }
  14102. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14103. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14104. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14105. }
  14106. else {
  14107. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14108. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14109. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14110. }
  14111. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14112. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14113. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14114. return texture;
  14115. };
  14116. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14117. var _this = this;
  14118. if (onLoad === void 0) { onLoad = null; }
  14119. if (onError === void 0) { onError = null; }
  14120. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14121. if (invertY === void 0) { invertY = false; }
  14122. var gl = this._gl;
  14123. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14124. scene._addPendingData(texture);
  14125. texture.url = url;
  14126. this._internalTexturesCache.push(texture);
  14127. var onerror = function (request, exception) {
  14128. scene._removePendingData(texture);
  14129. if (onError && request) {
  14130. onError(request.status + " " + request.statusText, exception);
  14131. }
  14132. };
  14133. var internalCallback = function (data) {
  14134. var width = texture.width;
  14135. var faceDataArrays = callback(data);
  14136. if (!faceDataArrays) {
  14137. return;
  14138. }
  14139. if (mipmmapGenerator) {
  14140. var textureType = _this._getWebGLTextureType(type);
  14141. var internalFormat = _this._getInternalFormat(format);
  14142. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14143. var needConversion = false;
  14144. if (internalFormat === gl.RGB) {
  14145. internalFormat = gl.RGBA;
  14146. needConversion = true;
  14147. }
  14148. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14149. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14150. var mipData = mipmmapGenerator(faceDataArrays);
  14151. for (var level = 0; level < mipData.length; level++) {
  14152. var mipSize = width >> level;
  14153. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14154. var mipFaceData = mipData[level][faceIndex];
  14155. if (needConversion) {
  14156. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14157. }
  14158. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14159. }
  14160. }
  14161. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14162. }
  14163. else {
  14164. texture.generateMipMaps = !noMipmap;
  14165. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14166. }
  14167. texture.isReady = true;
  14168. // this.resetTextureCache();
  14169. scene._removePendingData(texture);
  14170. if (onLoad) {
  14171. onLoad();
  14172. }
  14173. };
  14174. this._loadFile(url, function (data) {
  14175. internalCallback(data);
  14176. }, undefined, scene.database, true, onerror);
  14177. return texture;
  14178. };
  14179. ;
  14180. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14181. if (compression === void 0) { compression = null; }
  14182. var internalFormat = this._getInternalFormat(format);
  14183. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14184. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14185. if (!this._doNotHandleContextLost) {
  14186. texture._bufferView = data;
  14187. texture.format = format;
  14188. texture.invertY = invertY;
  14189. texture._compression = compression;
  14190. }
  14191. if (texture.width % 4 !== 0) {
  14192. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14193. }
  14194. if (compression && data) {
  14195. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14196. }
  14197. else {
  14198. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14199. }
  14200. if (texture.generateMipMaps) {
  14201. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14202. }
  14203. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14204. // this.resetTextureCache();
  14205. texture.isReady = true;
  14206. };
  14207. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14208. if (compression === void 0) { compression = null; }
  14209. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14210. texture.baseWidth = width;
  14211. texture.baseHeight = height;
  14212. texture.baseDepth = depth;
  14213. texture.width = width;
  14214. texture.height = height;
  14215. texture.depth = depth;
  14216. texture.format = format;
  14217. texture.generateMipMaps = generateMipMaps;
  14218. texture.samplingMode = samplingMode;
  14219. texture.is3D = true;
  14220. if (!this._doNotHandleContextLost) {
  14221. texture._bufferView = data;
  14222. }
  14223. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14224. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14225. // Filters
  14226. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14227. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14228. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14229. if (generateMipMaps) {
  14230. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14231. }
  14232. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14233. this._internalTexturesCache.push(texture);
  14234. return texture;
  14235. };
  14236. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14237. var gl = this._gl;
  14238. if (!gl) {
  14239. return;
  14240. }
  14241. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14242. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14243. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14244. if (!noMipmap && !isCompressed) {
  14245. gl.generateMipmap(gl.TEXTURE_2D);
  14246. }
  14247. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14248. // this.resetTextureCache();
  14249. if (scene) {
  14250. scene._removePendingData(texture);
  14251. }
  14252. texture.onLoadedObservable.notifyObservers(texture);
  14253. texture.onLoadedObservable.clear();
  14254. };
  14255. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14256. var _this = this;
  14257. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14258. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14259. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14260. var gl = this._gl;
  14261. if (!gl) {
  14262. return;
  14263. }
  14264. if (!texture._webGLTexture) {
  14265. // this.resetTextureCache();
  14266. if (scene) {
  14267. scene._removePendingData(texture);
  14268. }
  14269. return;
  14270. }
  14271. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14272. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14273. texture.baseWidth = width;
  14274. texture.baseHeight = height;
  14275. texture.width = potWidth;
  14276. texture.height = potHeight;
  14277. texture.isReady = true;
  14278. if (processFunction(potWidth, potHeight, function () {
  14279. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14280. })) {
  14281. // Returning as texture needs extra async steps
  14282. return;
  14283. }
  14284. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14285. };
  14286. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14287. // Create new RGBA data container.
  14288. var rgbaData;
  14289. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14290. rgbaData = new Float32Array(width * height * 4);
  14291. }
  14292. else {
  14293. rgbaData = new Uint32Array(width * height * 4);
  14294. }
  14295. // Convert each pixel.
  14296. for (var x = 0; x < width; x++) {
  14297. for (var y = 0; y < height; y++) {
  14298. var index = (y * width + x) * 3;
  14299. var newIndex = (y * width + x) * 4;
  14300. // Map Old Value to new value.
  14301. rgbaData[newIndex + 0] = rgbData[index + 0];
  14302. rgbaData[newIndex + 1] = rgbData[index + 1];
  14303. rgbaData[newIndex + 2] = rgbData[index + 2];
  14304. // Add fully opaque alpha channel.
  14305. rgbaData[newIndex + 3] = 1;
  14306. }
  14307. }
  14308. return rgbaData;
  14309. };
  14310. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14311. var gl = this._gl;
  14312. if (texture._framebuffer) {
  14313. gl.deleteFramebuffer(texture._framebuffer);
  14314. texture._framebuffer = null;
  14315. }
  14316. if (texture._depthStencilBuffer) {
  14317. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14318. texture._depthStencilBuffer = null;
  14319. }
  14320. if (texture._MSAAFramebuffer) {
  14321. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14322. texture._MSAAFramebuffer = null;
  14323. }
  14324. if (texture._MSAARenderBuffer) {
  14325. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14326. texture._MSAARenderBuffer = null;
  14327. }
  14328. };
  14329. Engine.prototype._releaseTexture = function (texture) {
  14330. var gl = this._gl;
  14331. this._releaseFramebufferObjects(texture);
  14332. gl.deleteTexture(texture._webGLTexture);
  14333. // Unbind channels
  14334. this.unbindAllTextures();
  14335. var index = this._internalTexturesCache.indexOf(texture);
  14336. if (index !== -1) {
  14337. this._internalTexturesCache.splice(index, 1);
  14338. }
  14339. // Integrated fixed lod samplers.
  14340. if (texture._lodTextureHigh) {
  14341. texture._lodTextureHigh.dispose();
  14342. }
  14343. if (texture._lodTextureMid) {
  14344. texture._lodTextureMid.dispose();
  14345. }
  14346. if (texture._lodTextureLow) {
  14347. texture._lodTextureLow.dispose();
  14348. }
  14349. };
  14350. Engine.prototype.setProgram = function (program) {
  14351. if (this._currentProgram !== program) {
  14352. this._gl.useProgram(program);
  14353. this._currentProgram = program;
  14354. }
  14355. };
  14356. Engine.prototype.bindSamplers = function (effect) {
  14357. this.setProgram(effect.getProgram());
  14358. var samplers = effect.getSamplers();
  14359. for (var index = 0; index < samplers.length; index++) {
  14360. var uniform = effect.getUniform(samplers[index]);
  14361. if (uniform) {
  14362. this._boundUniforms[index] = uniform;
  14363. }
  14364. }
  14365. this._currentEffect = null;
  14366. };
  14367. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14368. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14369. return;
  14370. }
  14371. // Remove
  14372. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14373. // Bind last to it
  14374. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14375. // Bind to dummy
  14376. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14377. };
  14378. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14379. if (!internalTexture) {
  14380. return -1;
  14381. }
  14382. internalTexture._initialSlot = channel;
  14383. if (this.disableTextureBindingOptimization) {
  14384. if (channel !== internalTexture._designatedSlot) {
  14385. this._textureCollisions.addCount(1, false);
  14386. }
  14387. }
  14388. else {
  14389. if (channel !== internalTexture._designatedSlot) {
  14390. if (internalTexture._designatedSlot > -1) {
  14391. return internalTexture._designatedSlot;
  14392. }
  14393. else {
  14394. // No slot for this texture, let's pick a new one (if we find a free slot)
  14395. if (this._nextFreeTextureSlots.length) {
  14396. return this._nextFreeTextureSlots[0];
  14397. }
  14398. // We need to recycle the oldest bound texture, sorry.
  14399. this._textureCollisions.addCount(1, false);
  14400. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14401. }
  14402. }
  14403. }
  14404. return channel;
  14405. };
  14406. Engine.prototype._linkTrackers = function (previous, next) {
  14407. previous.next = next;
  14408. next.previous = previous;
  14409. };
  14410. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14411. var currentSlot = internalTexture._designatedSlot;
  14412. if (currentSlot === -1) {
  14413. return -1;
  14414. }
  14415. internalTexture._designatedSlot = -1;
  14416. if (this.disableTextureBindingOptimization) {
  14417. return -1;
  14418. }
  14419. // Remove from bound list
  14420. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14421. // Free the slot
  14422. this._boundTexturesCache[currentSlot] = null;
  14423. this._nextFreeTextureSlots.push(currentSlot);
  14424. return currentSlot;
  14425. };
  14426. Engine.prototype._activateCurrentTexture = function () {
  14427. if (this._currentTextureChannel !== this._activeChannel) {
  14428. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14429. this._currentTextureChannel = this._activeChannel;
  14430. }
  14431. };
  14432. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14433. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14434. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14435. this._activeChannel = texture._designatedSlot;
  14436. }
  14437. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14438. var isTextureForRendering = texture && texture._initialSlot > -1;
  14439. if (currentTextureBound !== texture) {
  14440. if (currentTextureBound) {
  14441. this._removeDesignatedSlot(currentTextureBound);
  14442. }
  14443. this._activateCurrentTexture();
  14444. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14445. this._boundTexturesCache[this._activeChannel] = texture;
  14446. if (texture) {
  14447. if (!this.disableTextureBindingOptimization) {
  14448. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14449. if (slotIndex > -1) {
  14450. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14451. }
  14452. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14453. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14454. }
  14455. texture._designatedSlot = this._activeChannel;
  14456. }
  14457. }
  14458. else if (forTextureDataUpdate) {
  14459. this._activateCurrentTexture();
  14460. }
  14461. if (isTextureForRendering && !forTextureDataUpdate) {
  14462. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14463. }
  14464. };
  14465. Engine.prototype._bindTexture = function (channel, texture) {
  14466. if (channel < 0) {
  14467. return;
  14468. }
  14469. if (texture) {
  14470. channel = this._getCorrectTextureChannel(channel, texture);
  14471. }
  14472. this._activeChannel = channel;
  14473. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14474. };
  14475. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14476. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14477. };
  14478. Engine.prototype.unbindAllTextures = function () {
  14479. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14480. this._activeChannel = channel;
  14481. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14482. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14483. if (this.webGLVersion > 1) {
  14484. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14485. }
  14486. }
  14487. };
  14488. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14489. if (channel < 0) {
  14490. return;
  14491. }
  14492. if (uniform) {
  14493. this._boundUniforms[channel] = uniform;
  14494. }
  14495. this._setTexture(channel, texture);
  14496. };
  14497. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14498. var uniform = this._boundUniforms[sourceSlot];
  14499. if (uniform._currentState === destination) {
  14500. return;
  14501. }
  14502. this._gl.uniform1i(uniform, destination);
  14503. uniform._currentState = destination;
  14504. };
  14505. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14506. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14507. // Not ready?
  14508. if (!texture) {
  14509. if (this._boundTexturesCache[channel] != null) {
  14510. this._activeChannel = channel;
  14511. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14512. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14513. if (this.webGLVersion > 1) {
  14514. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14515. }
  14516. }
  14517. return false;
  14518. }
  14519. // Video
  14520. if (texture.video) {
  14521. this._activeChannel = channel;
  14522. texture.update();
  14523. }
  14524. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14525. texture.delayLoad();
  14526. return false;
  14527. }
  14528. var internalTexture;
  14529. if (texture.isReady()) {
  14530. internalTexture = texture.getInternalTexture();
  14531. }
  14532. else if (texture.isCube) {
  14533. internalTexture = this.emptyCubeTexture;
  14534. }
  14535. else if (texture.is3D) {
  14536. internalTexture = this.emptyTexture3D;
  14537. }
  14538. else {
  14539. internalTexture = this.emptyTexture;
  14540. }
  14541. if (!isPartOfTextureArray) {
  14542. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14543. }
  14544. if (this._boundTexturesCache[channel] === internalTexture) {
  14545. this._moveBoundTextureOnTop(internalTexture);
  14546. if (!isPartOfTextureArray) {
  14547. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14548. }
  14549. return false;
  14550. }
  14551. this._activeChannel = channel;
  14552. if (internalTexture && internalTexture.is3D) {
  14553. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14554. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14555. internalTexture._cachedWrapU = texture.wrapU;
  14556. switch (texture.wrapU) {
  14557. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14558. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14559. break;
  14560. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14561. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14562. break;
  14563. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14564. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14565. break;
  14566. }
  14567. }
  14568. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14569. internalTexture._cachedWrapV = texture.wrapV;
  14570. switch (texture.wrapV) {
  14571. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14572. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14573. break;
  14574. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14575. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14576. break;
  14577. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14578. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14579. break;
  14580. }
  14581. }
  14582. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14583. internalTexture._cachedWrapR = texture.wrapR;
  14584. switch (texture.wrapR) {
  14585. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14586. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14587. break;
  14588. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14589. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14590. break;
  14591. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14592. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14593. break;
  14594. }
  14595. }
  14596. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14597. }
  14598. else if (internalTexture && internalTexture.isCube) {
  14599. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14600. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14601. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14602. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14603. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14604. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14605. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14606. }
  14607. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14608. }
  14609. else {
  14610. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14611. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14612. internalTexture._cachedWrapU = texture.wrapU;
  14613. switch (texture.wrapU) {
  14614. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14615. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14616. break;
  14617. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14618. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14619. break;
  14620. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14621. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14622. break;
  14623. }
  14624. }
  14625. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14626. internalTexture._cachedWrapV = texture.wrapV;
  14627. switch (texture.wrapV) {
  14628. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14629. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14630. break;
  14631. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14632. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14633. break;
  14634. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14635. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14636. break;
  14637. }
  14638. }
  14639. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14640. }
  14641. return true;
  14642. };
  14643. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14644. if (channel < 0 || !uniform) {
  14645. return;
  14646. }
  14647. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14648. this._textureUnits = new Int32Array(textures.length);
  14649. }
  14650. for (var i = 0; i < textures.length; i++) {
  14651. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14652. }
  14653. this._gl.uniform1iv(uniform, this._textureUnits);
  14654. for (var index = 0; index < textures.length; index++) {
  14655. this._setTexture(this._textureUnits[index], textures[index], true);
  14656. }
  14657. };
  14658. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14659. var internalTexture = texture.getInternalTexture();
  14660. if (!internalTexture) {
  14661. return;
  14662. }
  14663. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14664. var value = texture.anisotropicFilteringLevel;
  14665. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14666. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14667. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14668. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14669. }
  14670. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14671. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14672. internalTexture._cachedAnisotropicFilteringLevel = value;
  14673. }
  14674. };
  14675. Engine.prototype.readPixels = function (x, y, width, height) {
  14676. var data = new Uint8Array(height * width * 4);
  14677. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14678. return data;
  14679. };
  14680. /**
  14681. * Add an externaly attached data from its key.
  14682. * This method call will fail and return false, if such key already exists.
  14683. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14684. * @param key the unique key that identifies the data
  14685. * @param data the data object to associate to the key for this Engine instance
  14686. * @return true if no such key were already present and the data was added successfully, false otherwise
  14687. */
  14688. Engine.prototype.addExternalData = function (key, data) {
  14689. if (!this._externalData) {
  14690. this._externalData = new BABYLON.StringDictionary();
  14691. }
  14692. return this._externalData.add(key, data);
  14693. };
  14694. /**
  14695. * Get an externaly attached data from its key
  14696. * @param key the unique key that identifies the data
  14697. * @return the associated data, if present (can be null), or undefined if not present
  14698. */
  14699. Engine.prototype.getExternalData = function (key) {
  14700. if (!this._externalData) {
  14701. this._externalData = new BABYLON.StringDictionary();
  14702. }
  14703. return this._externalData.get(key);
  14704. };
  14705. /**
  14706. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14707. * @param key the unique key that identifies the data
  14708. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14709. * @return the associated data, can be null if the factory returned null.
  14710. */
  14711. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14712. if (!this._externalData) {
  14713. this._externalData = new BABYLON.StringDictionary();
  14714. }
  14715. return this._externalData.getOrAddWithFactory(key, factory);
  14716. };
  14717. /**
  14718. * Remove an externaly attached data from the Engine instance
  14719. * @param key the unique key that identifies the data
  14720. * @return true if the data was successfully removed, false if it doesn't exist
  14721. */
  14722. Engine.prototype.removeExternalData = function (key) {
  14723. if (!this._externalData) {
  14724. this._externalData = new BABYLON.StringDictionary();
  14725. }
  14726. return this._externalData.remove(key);
  14727. };
  14728. Engine.prototype.unbindAllAttributes = function () {
  14729. if (this._mustWipeVertexAttributes) {
  14730. this._mustWipeVertexAttributes = false;
  14731. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14732. this._gl.disableVertexAttribArray(i);
  14733. this._vertexAttribArraysEnabled[i] = false;
  14734. this._currentBufferPointers[i].active = false;
  14735. }
  14736. return;
  14737. }
  14738. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14739. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14740. continue;
  14741. }
  14742. this._gl.disableVertexAttribArray(i);
  14743. this._vertexAttribArraysEnabled[i] = false;
  14744. this._currentBufferPointers[i].active = false;
  14745. }
  14746. };
  14747. Engine.prototype.releaseEffects = function () {
  14748. for (var name in this._compiledEffects) {
  14749. this._deleteProgram(this._compiledEffects[name]._program);
  14750. }
  14751. this._compiledEffects = {};
  14752. };
  14753. // Dispose
  14754. Engine.prototype.dispose = function () {
  14755. this.hideLoadingUI();
  14756. this.stopRenderLoop();
  14757. // Release postProcesses
  14758. while (this.postProcesses.length) {
  14759. this.postProcesses[0].dispose();
  14760. }
  14761. // Empty texture
  14762. if (this._emptyTexture) {
  14763. this._releaseTexture(this._emptyTexture);
  14764. this._emptyTexture = null;
  14765. }
  14766. if (this._emptyCubeTexture) {
  14767. this._releaseTexture(this._emptyCubeTexture);
  14768. this._emptyCubeTexture = null;
  14769. }
  14770. // Rescale PP
  14771. if (this._rescalePostProcess) {
  14772. this._rescalePostProcess.dispose();
  14773. }
  14774. // Release scenes
  14775. while (this.scenes.length) {
  14776. this.scenes[0].dispose();
  14777. }
  14778. // Release audio engine
  14779. if (Engine.audioEngine) {
  14780. Engine.audioEngine.dispose();
  14781. }
  14782. // Release effects
  14783. this.releaseEffects();
  14784. // Unbind
  14785. this.unbindAllAttributes();
  14786. if (this._dummyFramebuffer) {
  14787. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14788. }
  14789. //WebVR
  14790. this.disableVR();
  14791. // Events
  14792. if (BABYLON.Tools.IsWindowObjectExist()) {
  14793. window.removeEventListener("blur", this._onBlur);
  14794. window.removeEventListener("focus", this._onFocus);
  14795. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14796. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14797. if (this._renderingCanvas) {
  14798. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14799. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14800. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  14801. if (!this._doNotHandleContextLost) {
  14802. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14803. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14804. }
  14805. }
  14806. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14807. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14808. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14809. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14810. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14811. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14812. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14813. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14814. if (this._onVrDisplayConnect) {
  14815. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14816. if (this._onVrDisplayDisconnect) {
  14817. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14818. }
  14819. if (this._onVrDisplayPresentChange) {
  14820. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14821. }
  14822. this._onVrDisplayConnect = null;
  14823. this._onVrDisplayDisconnect = null;
  14824. }
  14825. }
  14826. // Remove from Instances
  14827. var index = Engine.Instances.indexOf(this);
  14828. if (index >= 0) {
  14829. Engine.Instances.splice(index, 1);
  14830. }
  14831. this._workingCanvas = null;
  14832. this._workingContext = null;
  14833. this._currentBufferPointers = [];
  14834. this._renderingCanvas = null;
  14835. this._currentProgram = null;
  14836. this._bindedRenderFunction = null;
  14837. this.onResizeObservable.clear();
  14838. this.onCanvasBlurObservable.clear();
  14839. this.onCanvasFocusObservable.clear();
  14840. this.onCanvasPointerOutObservable.clear();
  14841. this.onBeginFrameObservable.clear();
  14842. this.onEndFrameObservable.clear();
  14843. BABYLON.Effect.ResetCache();
  14844. // Abort active requests
  14845. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14846. var request = _a[_i];
  14847. request.abort();
  14848. }
  14849. };
  14850. // Loading screen
  14851. Engine.prototype.displayLoadingUI = function () {
  14852. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14853. return;
  14854. }
  14855. var loadingScreen = this.loadingScreen;
  14856. if (loadingScreen) {
  14857. loadingScreen.displayLoadingUI();
  14858. }
  14859. };
  14860. Engine.prototype.hideLoadingUI = function () {
  14861. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14862. return;
  14863. }
  14864. var loadingScreen = this.loadingScreen;
  14865. if (loadingScreen) {
  14866. loadingScreen.hideLoadingUI();
  14867. }
  14868. };
  14869. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14870. get: function () {
  14871. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14872. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14873. return this._loadingScreen;
  14874. },
  14875. set: function (loadingScreen) {
  14876. this._loadingScreen = loadingScreen;
  14877. },
  14878. enumerable: true,
  14879. configurable: true
  14880. });
  14881. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14882. set: function (text) {
  14883. this.loadingScreen.loadingUIText = text;
  14884. },
  14885. enumerable: true,
  14886. configurable: true
  14887. });
  14888. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14889. set: function (color) {
  14890. this.loadingScreen.loadingUIBackgroundColor = color;
  14891. },
  14892. enumerable: true,
  14893. configurable: true
  14894. });
  14895. Engine.prototype.attachContextLostEvent = function (callback) {
  14896. if (this._renderingCanvas) {
  14897. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14898. }
  14899. };
  14900. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14901. if (this._renderingCanvas) {
  14902. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14903. }
  14904. };
  14905. Engine.prototype.getVertexShaderSource = function (program) {
  14906. var shaders = this._gl.getAttachedShaders(program);
  14907. if (!shaders) {
  14908. return null;
  14909. }
  14910. return this._gl.getShaderSource(shaders[0]);
  14911. };
  14912. Engine.prototype.getFragmentShaderSource = function (program) {
  14913. var shaders = this._gl.getAttachedShaders(program);
  14914. if (!shaders) {
  14915. return null;
  14916. }
  14917. return this._gl.getShaderSource(shaders[1]);
  14918. };
  14919. Engine.prototype.getError = function () {
  14920. return this._gl.getError();
  14921. };
  14922. // FPS
  14923. Engine.prototype.getFps = function () {
  14924. return this._fps;
  14925. };
  14926. Engine.prototype.getDeltaTime = function () {
  14927. return this._deltaTime;
  14928. };
  14929. Engine.prototype._measureFps = function () {
  14930. this._performanceMonitor.sampleFrame();
  14931. this._fps = this._performanceMonitor.averageFPS;
  14932. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14933. };
  14934. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14935. if (faceIndex === void 0) { faceIndex = -1; }
  14936. var gl = this._gl;
  14937. if (!this._dummyFramebuffer) {
  14938. var dummy = gl.createFramebuffer();
  14939. if (!dummy) {
  14940. throw new Error("Unable to create dummy framebuffer");
  14941. }
  14942. this._dummyFramebuffer = dummy;
  14943. }
  14944. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14945. if (faceIndex > -1) {
  14946. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14947. }
  14948. else {
  14949. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14950. }
  14951. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14952. var buffer;
  14953. switch (readType) {
  14954. case gl.UNSIGNED_BYTE:
  14955. buffer = new Uint8Array(4 * width * height);
  14956. readType = gl.UNSIGNED_BYTE;
  14957. break;
  14958. default:
  14959. buffer = new Float32Array(4 * width * height);
  14960. readType = gl.FLOAT;
  14961. break;
  14962. }
  14963. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14964. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14965. return buffer;
  14966. };
  14967. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14968. if (this._webGLVersion > 1) {
  14969. return this._caps.colorBufferFloat;
  14970. }
  14971. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14972. };
  14973. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14974. if (this._webGLVersion > 1) {
  14975. return this._caps.colorBufferFloat;
  14976. }
  14977. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14978. };
  14979. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14980. Engine.prototype._canRenderToFramebuffer = function (type) {
  14981. var gl = this._gl;
  14982. //clear existing errors
  14983. while (gl.getError() !== gl.NO_ERROR) { }
  14984. var successful = true;
  14985. var texture = gl.createTexture();
  14986. gl.bindTexture(gl.TEXTURE_2D, texture);
  14987. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14988. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14989. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14990. var fb = gl.createFramebuffer();
  14991. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14992. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14993. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14994. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14995. successful = successful && (gl.getError() === gl.NO_ERROR);
  14996. //try render by clearing frame buffer's color buffer
  14997. if (successful) {
  14998. gl.clear(gl.COLOR_BUFFER_BIT);
  14999. successful = successful && (gl.getError() === gl.NO_ERROR);
  15000. }
  15001. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15002. if (successful) {
  15003. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15004. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15005. var readFormat = gl.RGBA;
  15006. var readType = gl.UNSIGNED_BYTE;
  15007. var buffer = new Uint8Array(4);
  15008. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15009. successful = successful && (gl.getError() === gl.NO_ERROR);
  15010. }
  15011. //clean up
  15012. gl.deleteTexture(texture);
  15013. gl.deleteFramebuffer(fb);
  15014. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15015. //clear accumulated errors
  15016. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15017. return successful;
  15018. };
  15019. Engine.prototype._getWebGLTextureType = function (type) {
  15020. if (type === Engine.TEXTURETYPE_FLOAT) {
  15021. return this._gl.FLOAT;
  15022. }
  15023. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15024. // Add Half Float Constant.
  15025. return this._gl.HALF_FLOAT_OES;
  15026. }
  15027. return this._gl.UNSIGNED_BYTE;
  15028. };
  15029. ;
  15030. Engine.prototype._getInternalFormat = function (format) {
  15031. var internalFormat = this._gl.RGBA;
  15032. switch (format) {
  15033. case Engine.TEXTUREFORMAT_ALPHA:
  15034. internalFormat = this._gl.ALPHA;
  15035. break;
  15036. case Engine.TEXTUREFORMAT_LUMINANCE:
  15037. internalFormat = this._gl.LUMINANCE;
  15038. break;
  15039. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15040. internalFormat = this._gl.LUMINANCE_ALPHA;
  15041. break;
  15042. case Engine.TEXTUREFORMAT_RGB:
  15043. case Engine.TEXTUREFORMAT_RGB32F:
  15044. internalFormat = this._gl.RGB;
  15045. break;
  15046. case Engine.TEXTUREFORMAT_RGBA:
  15047. case Engine.TEXTUREFORMAT_RGBA32F:
  15048. internalFormat = this._gl.RGBA;
  15049. break;
  15050. case Engine.TEXTUREFORMAT_R32F:
  15051. internalFormat = this._gl.RED;
  15052. break;
  15053. case Engine.TEXTUREFORMAT_RG32F:
  15054. internalFormat = this._gl.RG;
  15055. break;
  15056. }
  15057. return internalFormat;
  15058. };
  15059. /** @ignore */
  15060. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15061. if (this._webGLVersion === 1) {
  15062. if (format) {
  15063. switch (format) {
  15064. case Engine.TEXTUREFORMAT_LUMINANCE:
  15065. return this._gl.LUMINANCE;
  15066. }
  15067. }
  15068. return this._gl.RGBA;
  15069. }
  15070. if (type === Engine.TEXTURETYPE_FLOAT) {
  15071. if (format) {
  15072. switch (format) {
  15073. case Engine.TEXTUREFORMAT_R32F:
  15074. return this._gl.R32F;
  15075. case Engine.TEXTUREFORMAT_RG32F:
  15076. return this._gl.RG32F;
  15077. case Engine.TEXTUREFORMAT_RGB32F:
  15078. return this._gl.RGB32F;
  15079. }
  15080. }
  15081. return this._gl.RGBA32F;
  15082. }
  15083. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15084. return this._gl.RGBA16F;
  15085. }
  15086. if (format) {
  15087. switch (format) {
  15088. case Engine.TEXTUREFORMAT_LUMINANCE:
  15089. return this._gl.LUMINANCE;
  15090. }
  15091. }
  15092. return this._gl.RGBA;
  15093. };
  15094. ;
  15095. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15096. if (type === Engine.TEXTURETYPE_FLOAT) {
  15097. return this._gl.RGBA32F;
  15098. }
  15099. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15100. return this._gl.RGBA16F;
  15101. }
  15102. return this._gl.RGBA8;
  15103. };
  15104. ;
  15105. Engine.prototype.createQuery = function () {
  15106. return this._gl.createQuery();
  15107. };
  15108. Engine.prototype.deleteQuery = function (query) {
  15109. this._gl.deleteQuery(query);
  15110. return this;
  15111. };
  15112. Engine.prototype.isQueryResultAvailable = function (query) {
  15113. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15114. };
  15115. Engine.prototype.getQueryResult = function (query) {
  15116. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15117. };
  15118. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15119. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15120. this._gl.beginQuery(glAlgorithm, query);
  15121. return this;
  15122. };
  15123. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15124. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15125. this._gl.endQuery(glAlgorithm);
  15126. return this;
  15127. };
  15128. /* Time queries */
  15129. Engine.prototype._createTimeQuery = function () {
  15130. var timerQuery = this._caps.timerQuery;
  15131. if (timerQuery.createQueryEXT) {
  15132. return timerQuery.createQueryEXT();
  15133. }
  15134. return this.createQuery();
  15135. };
  15136. Engine.prototype._deleteTimeQuery = function (query) {
  15137. var timerQuery = this._caps.timerQuery;
  15138. if (timerQuery.deleteQueryEXT) {
  15139. timerQuery.deleteQueryEXT(query);
  15140. return;
  15141. }
  15142. this.deleteQuery(query);
  15143. };
  15144. Engine.prototype._getTimeQueryResult = function (query) {
  15145. var timerQuery = this._caps.timerQuery;
  15146. if (timerQuery.getQueryObjectEXT) {
  15147. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15148. }
  15149. return this.getQueryResult(query);
  15150. };
  15151. Engine.prototype._getTimeQueryAvailability = function (query) {
  15152. var timerQuery = this._caps.timerQuery;
  15153. if (timerQuery.getQueryObjectEXT) {
  15154. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15155. }
  15156. return this.isQueryResultAvailable(query);
  15157. };
  15158. Engine.prototype.startTimeQuery = function () {
  15159. var timerQuery = this._caps.timerQuery;
  15160. if (!timerQuery) {
  15161. return null;
  15162. }
  15163. var token = new BABYLON._TimeToken();
  15164. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15165. if (this._caps.canUseTimestampForTimerQuery) {
  15166. token._startTimeQuery = this._createTimeQuery();
  15167. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15168. }
  15169. else {
  15170. if (this._currentNonTimestampToken) {
  15171. return this._currentNonTimestampToken;
  15172. }
  15173. token._timeElapsedQuery = this._createTimeQuery();
  15174. if (timerQuery.beginQueryEXT) {
  15175. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15176. }
  15177. else {
  15178. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15179. }
  15180. this._currentNonTimestampToken = token;
  15181. }
  15182. return token;
  15183. };
  15184. Engine.prototype.endTimeQuery = function (token) {
  15185. var timerQuery = this._caps.timerQuery;
  15186. if (!timerQuery || !token) {
  15187. return -1;
  15188. }
  15189. if (this._caps.canUseTimestampForTimerQuery) {
  15190. if (!token._startTimeQuery) {
  15191. return -1;
  15192. }
  15193. if (!token._endTimeQuery) {
  15194. token._endTimeQuery = this._createTimeQuery();
  15195. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15196. }
  15197. }
  15198. else if (!token._timeElapsedQueryEnded) {
  15199. if (!token._timeElapsedQuery) {
  15200. return -1;
  15201. }
  15202. if (timerQuery.endQueryEXT) {
  15203. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15204. }
  15205. else {
  15206. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15207. }
  15208. token._timeElapsedQueryEnded = true;
  15209. }
  15210. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15211. var available = false;
  15212. if (token._endTimeQuery) {
  15213. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15214. }
  15215. else if (token._timeElapsedQuery) {
  15216. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15217. }
  15218. if (available && !disjoint) {
  15219. var result = 0;
  15220. if (this._caps.canUseTimestampForTimerQuery) {
  15221. if (!token._startTimeQuery || !token._endTimeQuery) {
  15222. return -1;
  15223. }
  15224. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15225. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15226. result = timeEnd - timeStart;
  15227. this._deleteTimeQuery(token._startTimeQuery);
  15228. this._deleteTimeQuery(token._endTimeQuery);
  15229. token._startTimeQuery = null;
  15230. token._endTimeQuery = null;
  15231. }
  15232. else {
  15233. if (!token._timeElapsedQuery) {
  15234. return -1;
  15235. }
  15236. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15237. this._deleteTimeQuery(token._timeElapsedQuery);
  15238. token._timeElapsedQuery = null;
  15239. token._timeElapsedQueryEnded = false;
  15240. this._currentNonTimestampToken = null;
  15241. }
  15242. return result;
  15243. }
  15244. return -1;
  15245. };
  15246. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15247. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15248. };
  15249. // Transform feedback
  15250. Engine.prototype.createTransformFeedback = function () {
  15251. return this._gl.createTransformFeedback();
  15252. };
  15253. Engine.prototype.deleteTransformFeedback = function (value) {
  15254. this._gl.deleteTransformFeedback(value);
  15255. };
  15256. Engine.prototype.bindTransformFeedback = function (value) {
  15257. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15258. };
  15259. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15260. if (usePoints === void 0) { usePoints = true; }
  15261. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15262. };
  15263. Engine.prototype.endTransformFeedback = function () {
  15264. this._gl.endTransformFeedback();
  15265. };
  15266. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15267. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15268. };
  15269. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15270. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15271. };
  15272. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15273. var _this = this;
  15274. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15275. this._activeRequests.push(request);
  15276. request.onCompleteObservable.add(function (request) {
  15277. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15278. });
  15279. return request;
  15280. };
  15281. /** @ignore */
  15282. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15283. var _this = this;
  15284. return new Promise(function (resolve, reject) {
  15285. _this._loadFile(url, function (data) {
  15286. resolve(data);
  15287. }, undefined, database, useArrayBuffer, function (request, exception) {
  15288. reject(exception);
  15289. });
  15290. });
  15291. };
  15292. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15293. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15294. var onload = function (data) {
  15295. loadedFiles[index] = data;
  15296. loadedFiles._internalCount++;
  15297. if (loadedFiles._internalCount === 6) {
  15298. onfinish(loadedFiles);
  15299. }
  15300. };
  15301. var onerror = function (request, exception) {
  15302. if (onErrorCallBack && request) {
  15303. onErrorCallBack(request.status + " " + request.statusText, exception);
  15304. }
  15305. };
  15306. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15307. };
  15308. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15309. if (onError === void 0) { onError = null; }
  15310. var loadedFiles = [];
  15311. loadedFiles._internalCount = 0;
  15312. for (var index = 0; index < 6; index++) {
  15313. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15314. }
  15315. };
  15316. // Statics
  15317. Engine.isSupported = function () {
  15318. try {
  15319. var tempcanvas = document.createElement("canvas");
  15320. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15321. return gl != null && !!window.WebGLRenderingContext;
  15322. }
  15323. catch (e) {
  15324. return false;
  15325. }
  15326. };
  15327. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15328. Engine.ExceptionList = [
  15329. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15330. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15331. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15332. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15333. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15334. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15335. ];
  15336. Engine.Instances = new Array();
  15337. // Const statics
  15338. Engine._ALPHA_DISABLE = 0;
  15339. Engine._ALPHA_ADD = 1;
  15340. Engine._ALPHA_COMBINE = 2;
  15341. Engine._ALPHA_SUBTRACT = 3;
  15342. Engine._ALPHA_MULTIPLY = 4;
  15343. Engine._ALPHA_MAXIMIZED = 5;
  15344. Engine._ALPHA_ONEONE = 6;
  15345. Engine._ALPHA_PREMULTIPLIED = 7;
  15346. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15347. Engine._ALPHA_INTERPOLATE = 9;
  15348. Engine._ALPHA_SCREENMODE = 10;
  15349. Engine._DELAYLOADSTATE_NONE = 0;
  15350. Engine._DELAYLOADSTATE_LOADED = 1;
  15351. Engine._DELAYLOADSTATE_LOADING = 2;
  15352. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15353. Engine._TEXTUREFORMAT_ALPHA = 0;
  15354. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15355. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15356. Engine._TEXTUREFORMAT_RGB = 4;
  15357. Engine._TEXTUREFORMAT_RGBA = 5;
  15358. Engine._TEXTUREFORMAT_R32F = 6;
  15359. Engine._TEXTUREFORMAT_RG32F = 7;
  15360. Engine._TEXTUREFORMAT_RGB32F = 8;
  15361. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15362. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15363. Engine._TEXTURETYPE_FLOAT = 1;
  15364. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15365. // Depht or Stencil test Constants.
  15366. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15367. 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.
  15368. 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.
  15369. 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.
  15370. 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.
  15371. 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.
  15372. 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.
  15373. 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.
  15374. // Stencil Actions Constants.
  15375. Engine._KEEP = 0x1E00;
  15376. Engine._REPLACE = 0x1E01;
  15377. Engine._INCR = 0x1E02;
  15378. Engine._DECR = 0x1E03;
  15379. Engine._INVERT = 0x150A;
  15380. Engine._INCR_WRAP = 0x8507;
  15381. Engine._DECR_WRAP = 0x8508;
  15382. // Texture rescaling mode
  15383. Engine._SCALEMODE_FLOOR = 1;
  15384. Engine._SCALEMODE_NEAREST = 2;
  15385. Engine._SCALEMODE_CEILING = 3;
  15386. // Updatable statics so stick with vars here
  15387. Engine.CollisionsEpsilon = 0.001;
  15388. Engine.CodeRepository = "src/";
  15389. Engine.ShadersRepository = "src/Shaders/";
  15390. return Engine;
  15391. }());
  15392. BABYLON.Engine = Engine;
  15393. })(BABYLON || (BABYLON = {}));
  15394. //# sourceMappingURL=babylon.engine.js.map
  15395. var BABYLON;
  15396. (function (BABYLON) {
  15397. /**
  15398. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15399. */
  15400. var Node = /** @class */ (function () {
  15401. /**
  15402. * Creates a new Node
  15403. * @param {string} name - the name and id to be given to this node
  15404. * @param {BABYLON.Scene} the scene this node will be added to
  15405. */
  15406. function Node(name, scene) {
  15407. if (scene === void 0) { scene = null; }
  15408. /**
  15409. * Gets or sets a string used to store user defined state for the node
  15410. */
  15411. this.state = "";
  15412. /**
  15413. * Gets or sets an object used to store user defined information for the node
  15414. */
  15415. this.metadata = null;
  15416. /**
  15417. * Gets or sets a boolean used to define if the node must be serialized
  15418. */
  15419. this.doNotSerialize = false;
  15420. /** @ignore */
  15421. this._isDisposed = false;
  15422. /**
  15423. * Gets a list of {BABYLON.Animation} associated with the node
  15424. */
  15425. this.animations = new Array();
  15426. this._ranges = {};
  15427. this._isEnabled = true;
  15428. this._isReady = true;
  15429. /** @ignore */
  15430. this._currentRenderId = -1;
  15431. this._parentRenderId = -1;
  15432. this._animationPropertiesOverride = null;
  15433. /**
  15434. * An event triggered when the mesh is disposed
  15435. * @type {BABYLON.Observable}
  15436. */
  15437. this.onDisposeObservable = new BABYLON.Observable();
  15438. // Behaviors
  15439. this._behaviors = new Array();
  15440. this.name = name;
  15441. this.id = name;
  15442. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15443. this.uniqueId = this._scene.getUniqueId();
  15444. this._initCache();
  15445. }
  15446. /**
  15447. * Gets a boolean indicating if the node has been disposed
  15448. * @returns true if the node was disposed
  15449. */
  15450. Node.prototype.isDisposed = function () {
  15451. return this._isDisposed;
  15452. };
  15453. Object.defineProperty(Node.prototype, "parent", {
  15454. get: function () {
  15455. return this._parentNode;
  15456. },
  15457. /**
  15458. * Gets or sets the parent of the node
  15459. */
  15460. set: function (parent) {
  15461. if (this._parentNode === parent) {
  15462. return;
  15463. }
  15464. // Remove self from list of children of parent
  15465. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15466. var index = this._parentNode._children.indexOf(this);
  15467. if (index !== -1) {
  15468. this._parentNode._children.splice(index, 1);
  15469. }
  15470. }
  15471. // Store new parent
  15472. this._parentNode = parent;
  15473. // Add as child to new parent
  15474. if (this._parentNode) {
  15475. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15476. this._parentNode._children = new Array();
  15477. }
  15478. this._parentNode._children.push(this);
  15479. }
  15480. },
  15481. enumerable: true,
  15482. configurable: true
  15483. });
  15484. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15485. /**
  15486. * Gets or sets the animation properties override
  15487. */
  15488. get: function () {
  15489. return this._animationPropertiesOverride;
  15490. },
  15491. set: function (value) {
  15492. this._animationPropertiesOverride = value;
  15493. },
  15494. enumerable: true,
  15495. configurable: true
  15496. });
  15497. /**
  15498. * Gets a string idenfifying the name of the class
  15499. * @returns "Node" string
  15500. */
  15501. Node.prototype.getClassName = function () {
  15502. return "Node";
  15503. };
  15504. Object.defineProperty(Node.prototype, "onDispose", {
  15505. /**
  15506. * Sets a callback that will be raised when the node will be disposed
  15507. */
  15508. set: function (callback) {
  15509. if (this._onDisposeObserver) {
  15510. this.onDisposeObservable.remove(this._onDisposeObserver);
  15511. }
  15512. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15513. },
  15514. enumerable: true,
  15515. configurable: true
  15516. });
  15517. /**
  15518. * Gets the scene of the node
  15519. * @returns a {BABYLON.Scene}
  15520. */
  15521. Node.prototype.getScene = function () {
  15522. return this._scene;
  15523. };
  15524. /**
  15525. * Gets the engine of the node
  15526. * @returns a {BABYLON.Engine}
  15527. */
  15528. Node.prototype.getEngine = function () {
  15529. return this._scene.getEngine();
  15530. };
  15531. /**
  15532. * Attach a behavior to the node
  15533. * @see http://doc.babylonjs.com/features/behaviour
  15534. * @param behavior defines the behavior to attach
  15535. * @returns the current Node
  15536. */
  15537. Node.prototype.addBehavior = function (behavior) {
  15538. var _this = this;
  15539. var index = this._behaviors.indexOf(behavior);
  15540. if (index !== -1) {
  15541. return this;
  15542. }
  15543. behavior.init();
  15544. if (this._scene.isLoading) {
  15545. // We defer the attach when the scene will be loaded
  15546. var observer = this._scene.onDataLoadedObservable.add(function () {
  15547. behavior.attach(_this);
  15548. setTimeout(function () {
  15549. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15550. _this._scene.onDataLoadedObservable.remove(observer);
  15551. }, 0);
  15552. });
  15553. }
  15554. else {
  15555. behavior.attach(this);
  15556. }
  15557. this._behaviors.push(behavior);
  15558. return this;
  15559. };
  15560. /**
  15561. * Remove an attached behavior
  15562. * @see http://doc.babylonjs.com/features/behaviour
  15563. * @param behavior defines the behavior to attach
  15564. * @returns the current Node
  15565. */
  15566. Node.prototype.removeBehavior = function (behavior) {
  15567. var index = this._behaviors.indexOf(behavior);
  15568. if (index === -1) {
  15569. return this;
  15570. }
  15571. this._behaviors[index].detach();
  15572. this._behaviors.splice(index, 1);
  15573. return this;
  15574. };
  15575. Object.defineProperty(Node.prototype, "behaviors", {
  15576. /**
  15577. * Gets the list of attached behaviors
  15578. * @see http://doc.babylonjs.com/features/behaviour
  15579. */
  15580. get: function () {
  15581. return this._behaviors;
  15582. },
  15583. enumerable: true,
  15584. configurable: true
  15585. });
  15586. /**
  15587. * Gets an attached behavior by name
  15588. * @param name defines the name of the behavior to look for
  15589. * @see http://doc.babylonjs.com/features/behaviour
  15590. * @returns null if behavior was not found else the requested behavior
  15591. */
  15592. Node.prototype.getBehaviorByName = function (name) {
  15593. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15594. var behavior = _a[_i];
  15595. if (behavior.name === name) {
  15596. return behavior;
  15597. }
  15598. }
  15599. return null;
  15600. };
  15601. /**
  15602. * Returns the world matrix of the node
  15603. * @returns a matrix containing the node's world matrix
  15604. */
  15605. Node.prototype.getWorldMatrix = function () {
  15606. return BABYLON.Matrix.Identity();
  15607. };
  15608. // override it in derived class if you add new variables to the cache
  15609. // and call the parent class method
  15610. /** @ignore */
  15611. Node.prototype._initCache = function () {
  15612. this._cache = {};
  15613. this._cache.parent = undefined;
  15614. };
  15615. /** @ignore */
  15616. Node.prototype.updateCache = function (force) {
  15617. if (!force && this.isSynchronized())
  15618. return;
  15619. this._cache.parent = this.parent;
  15620. this._updateCache();
  15621. };
  15622. // override it in derived class if you add new variables to the cache
  15623. // and call the parent class method if !ignoreParentClass
  15624. /** @ignore */
  15625. Node.prototype._updateCache = function (ignoreParentClass) {
  15626. };
  15627. // override it in derived class if you add new variables to the cache
  15628. /** @ignore */
  15629. Node.prototype._isSynchronized = function () {
  15630. return true;
  15631. };
  15632. /** @ignore */
  15633. Node.prototype._markSyncedWithParent = function () {
  15634. if (this.parent) {
  15635. this._parentRenderId = this.parent._currentRenderId;
  15636. }
  15637. };
  15638. /** @ignore */
  15639. Node.prototype.isSynchronizedWithParent = function () {
  15640. if (!this.parent) {
  15641. return true;
  15642. }
  15643. if (this._parentRenderId !== this.parent._currentRenderId) {
  15644. return false;
  15645. }
  15646. return this.parent.isSynchronized();
  15647. };
  15648. /** @ignore */
  15649. Node.prototype.isSynchronized = function (updateCache) {
  15650. var check = this.hasNewParent();
  15651. check = check || !this.isSynchronizedWithParent();
  15652. check = check || !this._isSynchronized();
  15653. if (updateCache)
  15654. this.updateCache(true);
  15655. return !check;
  15656. };
  15657. /** @ignore */
  15658. Node.prototype.hasNewParent = function (update) {
  15659. if (this._cache.parent === this.parent)
  15660. return false;
  15661. if (update)
  15662. this._cache.parent = this.parent;
  15663. return true;
  15664. };
  15665. /**
  15666. * Is this node ready to be used/rendered
  15667. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15668. * @return true if the node is ready
  15669. */
  15670. Node.prototype.isReady = function (completeCheck) {
  15671. if (completeCheck === void 0) { completeCheck = false; }
  15672. return this._isReady;
  15673. };
  15674. /**
  15675. * Is this node enabled?
  15676. * 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
  15677. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  15678. * @return whether this node (and its parent) is enabled
  15679. * @see setEnabled
  15680. */
  15681. Node.prototype.isEnabled = function (checkAncestors) {
  15682. if (checkAncestors === void 0) { checkAncestors = true; }
  15683. if (checkAncestors === false) {
  15684. return this._isEnabled;
  15685. }
  15686. if (this._isEnabled === false) {
  15687. return false;
  15688. }
  15689. if (this.parent !== undefined && this.parent !== null) {
  15690. return this.parent.isEnabled(checkAncestors);
  15691. }
  15692. return true;
  15693. };
  15694. /**
  15695. * Set the enabled state of this node
  15696. * @param value defines the new enabled state
  15697. * @see isEnabled
  15698. */
  15699. Node.prototype.setEnabled = function (value) {
  15700. this._isEnabled = value;
  15701. };
  15702. /**
  15703. * Is this node a descendant of the given node?
  15704. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15705. * @param ancestor defines the parent node to inspect
  15706. * @see parent
  15707. * @returns a boolean indicating if this node is a descendant of the given node
  15708. */
  15709. Node.prototype.isDescendantOf = function (ancestor) {
  15710. if (this.parent) {
  15711. if (this.parent === ancestor) {
  15712. return true;
  15713. }
  15714. return this.parent.isDescendantOf(ancestor);
  15715. }
  15716. return false;
  15717. };
  15718. /** @ignore */
  15719. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15720. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15721. if (!this._children) {
  15722. return;
  15723. }
  15724. for (var index = 0; index < this._children.length; index++) {
  15725. var item = this._children[index];
  15726. if (!predicate || predicate(item)) {
  15727. results.push(item);
  15728. }
  15729. if (!directDescendantsOnly) {
  15730. item._getDescendants(results, false, predicate);
  15731. }
  15732. }
  15733. };
  15734. /**
  15735. * Will return all nodes that have this node as ascendant
  15736. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15737. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15738. * @return all children nodes of all types
  15739. */
  15740. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15741. var results = new Array();
  15742. this._getDescendants(results, directDescendantsOnly, predicate);
  15743. return results;
  15744. };
  15745. /**
  15746. * Get all child-meshes of this node
  15747. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15748. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15749. * @returns an array of {BABYLON.AbstractMesh}
  15750. */
  15751. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15752. var results = [];
  15753. this._getDescendants(results, directDescendantsOnly, function (node) {
  15754. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15755. });
  15756. return results;
  15757. };
  15758. /**
  15759. * Get all child-transformNodes of this node
  15760. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15761. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15762. * @returns an array of {BABYLON.TransformNode}
  15763. */
  15764. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15765. var results = [];
  15766. this._getDescendants(results, directDescendantsOnly, function (node) {
  15767. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15768. });
  15769. return results;
  15770. };
  15771. /**
  15772. * Get all direct children of this node
  15773. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15774. * @returns an array of {BABYLON.Node}
  15775. */
  15776. Node.prototype.getChildren = function (predicate) {
  15777. return this.getDescendants(true, predicate);
  15778. };
  15779. /** @ignore */
  15780. Node.prototype._setReady = function (state) {
  15781. if (state === this._isReady) {
  15782. return;
  15783. }
  15784. if (!state) {
  15785. this._isReady = false;
  15786. return;
  15787. }
  15788. this._isReady = true;
  15789. if (this.onReady) {
  15790. this.onReady(this);
  15791. }
  15792. };
  15793. /**
  15794. * Get an animation by name
  15795. * @param name defines the name of the animation to look for
  15796. * @returns null if not found else the requested animation
  15797. */
  15798. Node.prototype.getAnimationByName = function (name) {
  15799. for (var i = 0; i < this.animations.length; i++) {
  15800. var animation = this.animations[i];
  15801. if (animation.name === name) {
  15802. return animation;
  15803. }
  15804. }
  15805. return null;
  15806. };
  15807. /**
  15808. * Creates an animation range for this node
  15809. * @param name defines the name of the range
  15810. * @param from defines the starting key
  15811. * @param to defines the end key
  15812. */
  15813. Node.prototype.createAnimationRange = function (name, from, to) {
  15814. // check name not already in use
  15815. if (!this._ranges[name]) {
  15816. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15817. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15818. if (this.animations[i]) {
  15819. this.animations[i].createRange(name, from, to);
  15820. }
  15821. }
  15822. }
  15823. };
  15824. /**
  15825. * Delete a specific animation range
  15826. * @param name defines the name of the range to delete
  15827. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15828. */
  15829. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15830. if (deleteFrames === void 0) { deleteFrames = true; }
  15831. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15832. if (this.animations[i]) {
  15833. this.animations[i].deleteRange(name, deleteFrames);
  15834. }
  15835. }
  15836. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15837. };
  15838. /**
  15839. * Get an animation range by name
  15840. * @param name defines the name of the animation range to look for
  15841. * @returns null if not found else the requested animation range
  15842. */
  15843. Node.prototype.getAnimationRange = function (name) {
  15844. return this._ranges[name];
  15845. };
  15846. /**
  15847. * Will start the animation sequence
  15848. * @param name defines the range frames for animation sequence
  15849. * @param loop defines if the animation should loop (false by default)
  15850. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15851. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15852. * @returns the object created for this animation. If range does not exist, it will return null
  15853. */
  15854. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15855. var range = this.getAnimationRange(name);
  15856. if (!range) {
  15857. return null;
  15858. }
  15859. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15860. };
  15861. /**
  15862. * Serialize animation ranges into a JSON compatible object
  15863. * @returns serialization object
  15864. */
  15865. Node.prototype.serializeAnimationRanges = function () {
  15866. var serializationRanges = [];
  15867. for (var name in this._ranges) {
  15868. var localRange = this._ranges[name];
  15869. if (!localRange) {
  15870. continue;
  15871. }
  15872. var range = {};
  15873. range.name = name;
  15874. range.from = localRange.from;
  15875. range.to = localRange.to;
  15876. serializationRanges.push(range);
  15877. }
  15878. return serializationRanges;
  15879. };
  15880. /**
  15881. * Computes the world matrix of the node
  15882. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15883. * @returns the world matrix
  15884. */
  15885. Node.prototype.computeWorldMatrix = function (force) {
  15886. return BABYLON.Matrix.Identity();
  15887. };
  15888. /**
  15889. * Releases resources associated with this node.
  15890. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  15891. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  15892. */
  15893. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15894. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15895. if (!doNotRecurse) {
  15896. var nodes = this.getDescendants(true);
  15897. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  15898. var node = nodes_1[_i];
  15899. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  15900. }
  15901. }
  15902. else {
  15903. var transformNodes = this.getChildTransformNodes(true);
  15904. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  15905. var transformNode = transformNodes_1[_a];
  15906. transformNode.parent = null;
  15907. transformNode.computeWorldMatrix(true);
  15908. }
  15909. }
  15910. this.parent = null;
  15911. // Callback
  15912. this.onDisposeObservable.notifyObservers(this);
  15913. this.onDisposeObservable.clear();
  15914. // Behaviors
  15915. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  15916. var behavior = _c[_b];
  15917. behavior.detach();
  15918. }
  15919. this._behaviors = [];
  15920. this._isDisposed = true;
  15921. };
  15922. /**
  15923. * Parse animation range data from a serialization object and store them into a given node
  15924. * @param node defines where to store the animation ranges
  15925. * @param parsedNode defines the serialization object to read data from
  15926. * @param scene defines the hosting scene
  15927. */
  15928. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15929. if (parsedNode.ranges) {
  15930. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15931. var data = parsedNode.ranges[index];
  15932. node.createAnimationRange(data.name, data.from, data.to);
  15933. }
  15934. }
  15935. };
  15936. __decorate([
  15937. BABYLON.serialize()
  15938. ], Node.prototype, "name", void 0);
  15939. __decorate([
  15940. BABYLON.serialize()
  15941. ], Node.prototype, "id", void 0);
  15942. __decorate([
  15943. BABYLON.serialize()
  15944. ], Node.prototype, "uniqueId", void 0);
  15945. __decorate([
  15946. BABYLON.serialize()
  15947. ], Node.prototype, "state", void 0);
  15948. __decorate([
  15949. BABYLON.serialize()
  15950. ], Node.prototype, "metadata", void 0);
  15951. return Node;
  15952. }());
  15953. BABYLON.Node = Node;
  15954. })(BABYLON || (BABYLON = {}));
  15955. //# sourceMappingURL=babylon.node.js.map
  15956. var BABYLON;
  15957. (function (BABYLON) {
  15958. var BoundingSphere = /** @class */ (function () {
  15959. function BoundingSphere(minimum, maximum) {
  15960. this.minimum = minimum;
  15961. this.maximum = maximum;
  15962. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15963. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15964. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15965. this.radius = distance * 0.5;
  15966. this.centerWorld = BABYLON.Vector3.Zero();
  15967. this._update(BABYLON.Matrix.Identity());
  15968. }
  15969. // Methods
  15970. BoundingSphere.prototype._update = function (world) {
  15971. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15972. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15973. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15974. };
  15975. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15976. for (var i = 0; i < 6; i++) {
  15977. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15978. return false;
  15979. }
  15980. return true;
  15981. };
  15982. BoundingSphere.prototype.intersectsPoint = function (point) {
  15983. var x = this.centerWorld.x - point.x;
  15984. var y = this.centerWorld.y - point.y;
  15985. var z = this.centerWorld.z - point.z;
  15986. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15987. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15988. return false;
  15989. return true;
  15990. };
  15991. // Statics
  15992. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15993. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15994. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15995. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15996. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15997. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15998. return false;
  15999. return true;
  16000. };
  16001. return BoundingSphere;
  16002. }());
  16003. BABYLON.BoundingSphere = BoundingSphere;
  16004. })(BABYLON || (BABYLON = {}));
  16005. //# sourceMappingURL=babylon.boundingSphere.js.map
  16006. var BABYLON;
  16007. (function (BABYLON) {
  16008. var BoundingBox = /** @class */ (function () {
  16009. function BoundingBox(minimum, maximum) {
  16010. this.minimum = minimum;
  16011. this.maximum = maximum;
  16012. this.vectors = new Array();
  16013. this.vectorsWorld = new Array();
  16014. // Bounding vectors
  16015. this.vectors.push(this.minimum.clone());
  16016. this.vectors.push(this.maximum.clone());
  16017. this.vectors.push(this.minimum.clone());
  16018. this.vectors[2].x = this.maximum.x;
  16019. this.vectors.push(this.minimum.clone());
  16020. this.vectors[3].y = this.maximum.y;
  16021. this.vectors.push(this.minimum.clone());
  16022. this.vectors[4].z = this.maximum.z;
  16023. this.vectors.push(this.maximum.clone());
  16024. this.vectors[5].z = this.minimum.z;
  16025. this.vectors.push(this.maximum.clone());
  16026. this.vectors[6].x = this.minimum.x;
  16027. this.vectors.push(this.maximum.clone());
  16028. this.vectors[7].y = this.minimum.y;
  16029. // OBB
  16030. this.center = this.maximum.add(this.minimum).scale(0.5);
  16031. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16032. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16033. // World
  16034. for (var index = 0; index < this.vectors.length; index++) {
  16035. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16036. }
  16037. this.minimumWorld = BABYLON.Vector3.Zero();
  16038. this.maximumWorld = BABYLON.Vector3.Zero();
  16039. this.centerWorld = BABYLON.Vector3.Zero();
  16040. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16041. this._update(BABYLON.Matrix.Identity());
  16042. }
  16043. // Methods
  16044. BoundingBox.prototype.getWorldMatrix = function () {
  16045. return this._worldMatrix;
  16046. };
  16047. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16048. this._worldMatrix.copyFrom(matrix);
  16049. return this;
  16050. };
  16051. BoundingBox.prototype._update = function (world) {
  16052. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16053. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16054. for (var index = 0; index < this.vectors.length; index++) {
  16055. var v = this.vectorsWorld[index];
  16056. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16057. if (v.x < this.minimumWorld.x)
  16058. this.minimumWorld.x = v.x;
  16059. if (v.y < this.minimumWorld.y)
  16060. this.minimumWorld.y = v.y;
  16061. if (v.z < this.minimumWorld.z)
  16062. this.minimumWorld.z = v.z;
  16063. if (v.x > this.maximumWorld.x)
  16064. this.maximumWorld.x = v.x;
  16065. if (v.y > this.maximumWorld.y)
  16066. this.maximumWorld.y = v.y;
  16067. if (v.z > this.maximumWorld.z)
  16068. this.maximumWorld.z = v.z;
  16069. }
  16070. // Extend
  16071. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16072. this.extendSizeWorld.scaleInPlace(0.5);
  16073. // OBB
  16074. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16075. this.centerWorld.scaleInPlace(0.5);
  16076. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16077. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16078. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16079. this._worldMatrix = world;
  16080. };
  16081. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16082. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16083. };
  16084. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16085. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16086. };
  16087. BoundingBox.prototype.intersectsPoint = function (point) {
  16088. var delta = -BABYLON.Epsilon;
  16089. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16090. return false;
  16091. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16092. return false;
  16093. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16094. return false;
  16095. return true;
  16096. };
  16097. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16098. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16099. };
  16100. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16101. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16102. return false;
  16103. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16104. return false;
  16105. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16106. return false;
  16107. return true;
  16108. };
  16109. // Statics
  16110. BoundingBox.Intersects = function (box0, box1) {
  16111. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16112. return false;
  16113. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16114. return false;
  16115. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16116. return false;
  16117. return true;
  16118. };
  16119. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16120. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16121. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16122. return (num <= (sphereRadius * sphereRadius));
  16123. };
  16124. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16125. for (var p = 0; p < 6; p++) {
  16126. for (var i = 0; i < 8; i++) {
  16127. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16128. return false;
  16129. }
  16130. }
  16131. }
  16132. return true;
  16133. };
  16134. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16135. for (var p = 0; p < 6; p++) {
  16136. var inCount = 8;
  16137. for (var i = 0; i < 8; i++) {
  16138. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16139. --inCount;
  16140. }
  16141. else {
  16142. break;
  16143. }
  16144. }
  16145. if (inCount === 0)
  16146. return false;
  16147. }
  16148. return true;
  16149. };
  16150. return BoundingBox;
  16151. }());
  16152. BABYLON.BoundingBox = BoundingBox;
  16153. })(BABYLON || (BABYLON = {}));
  16154. //# sourceMappingURL=babylon.boundingBox.js.map
  16155. var BABYLON;
  16156. (function (BABYLON) {
  16157. var computeBoxExtents = function (axis, box) {
  16158. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16159. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16160. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16161. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16162. var r = r0 + r1 + r2;
  16163. return {
  16164. min: p - r,
  16165. max: p + r
  16166. };
  16167. };
  16168. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16169. var axisOverlap = function (axis, box0, box1) {
  16170. var result0 = computeBoxExtents(axis, box0);
  16171. var result1 = computeBoxExtents(axis, box1);
  16172. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16173. };
  16174. var BoundingInfo = /** @class */ (function () {
  16175. function BoundingInfo(minimum, maximum) {
  16176. this.minimum = minimum;
  16177. this.maximum = maximum;
  16178. this._isLocked = false;
  16179. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16180. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16181. }
  16182. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16183. get: function () {
  16184. return this._isLocked;
  16185. },
  16186. set: function (value) {
  16187. this._isLocked = value;
  16188. },
  16189. enumerable: true,
  16190. configurable: true
  16191. });
  16192. // Methods
  16193. BoundingInfo.prototype.update = function (world) {
  16194. if (this._isLocked) {
  16195. return;
  16196. }
  16197. this.boundingBox._update(world);
  16198. this.boundingSphere._update(world);
  16199. };
  16200. /**
  16201. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16202. * @param center New center of the bounding info
  16203. * @param extend New extend of the bounding info
  16204. */
  16205. BoundingInfo.prototype.centerOn = function (center, extend) {
  16206. this.minimum = center.subtract(extend);
  16207. this.maximum = center.add(extend);
  16208. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16209. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16210. return this;
  16211. };
  16212. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16213. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16214. return false;
  16215. return this.boundingBox.isInFrustum(frustumPlanes);
  16216. };
  16217. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16218. /**
  16219. * Gets the world distance between the min and max points of the bounding box
  16220. */
  16221. get: function () {
  16222. var boundingBox = this.boundingBox;
  16223. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16224. return size.length();
  16225. },
  16226. enumerable: true,
  16227. configurable: true
  16228. });
  16229. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16230. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16231. };
  16232. BoundingInfo.prototype._checkCollision = function (collider) {
  16233. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16234. };
  16235. BoundingInfo.prototype.intersectsPoint = function (point) {
  16236. if (!this.boundingSphere.centerWorld) {
  16237. return false;
  16238. }
  16239. if (!this.boundingSphere.intersectsPoint(point)) {
  16240. return false;
  16241. }
  16242. if (!this.boundingBox.intersectsPoint(point)) {
  16243. return false;
  16244. }
  16245. return true;
  16246. };
  16247. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16248. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16249. return false;
  16250. }
  16251. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16252. return false;
  16253. }
  16254. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16255. return false;
  16256. }
  16257. if (!precise) {
  16258. return true;
  16259. }
  16260. var box0 = this.boundingBox;
  16261. var box1 = boundingInfo.boundingBox;
  16262. if (!axisOverlap(box0.directions[0], box0, box1))
  16263. return false;
  16264. if (!axisOverlap(box0.directions[1], box0, box1))
  16265. return false;
  16266. if (!axisOverlap(box0.directions[2], box0, box1))
  16267. return false;
  16268. if (!axisOverlap(box1.directions[0], box0, box1))
  16269. return false;
  16270. if (!axisOverlap(box1.directions[1], box0, box1))
  16271. return false;
  16272. if (!axisOverlap(box1.directions[2], box0, box1))
  16273. return false;
  16274. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16275. return false;
  16276. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16277. return false;
  16278. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16279. return false;
  16280. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16281. return false;
  16282. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16283. return false;
  16284. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16285. return false;
  16286. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16287. return false;
  16288. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16289. return false;
  16290. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16291. return false;
  16292. return true;
  16293. };
  16294. return BoundingInfo;
  16295. }());
  16296. BABYLON.BoundingInfo = BoundingInfo;
  16297. })(BABYLON || (BABYLON = {}));
  16298. //# sourceMappingURL=babylon.boundingInfo.js.map
  16299. var BABYLON;
  16300. (function (BABYLON) {
  16301. var TransformNode = /** @class */ (function (_super) {
  16302. __extends(TransformNode, _super);
  16303. function TransformNode(name, scene, isPure) {
  16304. if (scene === void 0) { scene = null; }
  16305. if (isPure === void 0) { isPure = true; }
  16306. var _this = _super.call(this, name, scene) || this;
  16307. // Properties
  16308. _this._rotation = BABYLON.Vector3.Zero();
  16309. _this._scaling = BABYLON.Vector3.One();
  16310. _this._isDirty = false;
  16311. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16312. _this.scalingDeterminant = 1;
  16313. _this.infiniteDistance = false;
  16314. _this.position = BABYLON.Vector3.Zero();
  16315. _this._localWorld = BABYLON.Matrix.Zero();
  16316. _this._worldMatrix = BABYLON.Matrix.Zero();
  16317. _this._worldMatrixDeterminant = 0;
  16318. _this._absolutePosition = BABYLON.Vector3.Zero();
  16319. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16320. _this._postMultiplyPivotMatrix = false;
  16321. _this._isWorldMatrixFrozen = false;
  16322. /**
  16323. * An event triggered after the world matrix is updated
  16324. * @type {BABYLON.Observable}
  16325. */
  16326. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16327. _this._nonUniformScaling = false;
  16328. if (isPure) {
  16329. _this.getScene().addTransformNode(_this);
  16330. }
  16331. return _this;
  16332. }
  16333. /**
  16334. * Gets a string idenfifying the name of the class
  16335. * @returns "TransformNode" string
  16336. */
  16337. TransformNode.prototype.getClassName = function () {
  16338. return "TransformNode";
  16339. };
  16340. Object.defineProperty(TransformNode.prototype, "rotation", {
  16341. /**
  16342. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16343. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16344. * Default : (0.0, 0.0, 0.0)
  16345. */
  16346. get: function () {
  16347. return this._rotation;
  16348. },
  16349. set: function (newRotation) {
  16350. this._rotation = newRotation;
  16351. },
  16352. enumerable: true,
  16353. configurable: true
  16354. });
  16355. Object.defineProperty(TransformNode.prototype, "scaling", {
  16356. /**
  16357. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16358. * Default : (1.0, 1.0, 1.0)
  16359. */
  16360. get: function () {
  16361. return this._scaling;
  16362. },
  16363. /**
  16364. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16365. * Default : (1.0, 1.0, 1.0)
  16366. */
  16367. set: function (newScaling) {
  16368. this._scaling = newScaling;
  16369. },
  16370. enumerable: true,
  16371. configurable: true
  16372. });
  16373. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16374. /**
  16375. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16376. * It's null by default.
  16377. * 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)
  16378. */
  16379. get: function () {
  16380. return this._rotationQuaternion;
  16381. },
  16382. set: function (quaternion) {
  16383. this._rotationQuaternion = quaternion;
  16384. //reset the rotation vector.
  16385. if (quaternion && this.rotation.length()) {
  16386. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16387. }
  16388. },
  16389. enumerable: true,
  16390. configurable: true
  16391. });
  16392. /**
  16393. * Returns the latest update of the World matrix
  16394. * Returns a Matrix.
  16395. */
  16396. TransformNode.prototype.getWorldMatrix = function () {
  16397. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16398. this.computeWorldMatrix();
  16399. }
  16400. return this._worldMatrix;
  16401. };
  16402. /**
  16403. * Returns the latest update of the World matrix determinant.
  16404. */
  16405. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16406. return this._worldMatrixDeterminant;
  16407. };
  16408. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16409. /**
  16410. * Returns directly the latest state of the mesh World matrix.
  16411. * A Matrix is returned.
  16412. */
  16413. get: function () {
  16414. return this._worldMatrix;
  16415. },
  16416. enumerable: true,
  16417. configurable: true
  16418. });
  16419. /**
  16420. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16421. * Returns the AbstractMesh.
  16422. */
  16423. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16424. this._poseMatrix.copyFrom(matrix);
  16425. return this;
  16426. };
  16427. /**
  16428. * Returns the mesh Pose matrix.
  16429. * Returned object : Matrix
  16430. */
  16431. TransformNode.prototype.getPoseMatrix = function () {
  16432. return this._poseMatrix;
  16433. };
  16434. TransformNode.prototype._isSynchronized = function () {
  16435. if (this._isDirty) {
  16436. return false;
  16437. }
  16438. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16439. return false;
  16440. if (this._cache.pivotMatrixUpdated) {
  16441. return false;
  16442. }
  16443. if (this.infiniteDistance) {
  16444. return false;
  16445. }
  16446. if (!this._cache.position.equals(this.position))
  16447. return false;
  16448. if (this.rotationQuaternion) {
  16449. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16450. return false;
  16451. }
  16452. if (!this._cache.rotation.equals(this.rotation))
  16453. return false;
  16454. if (!this._cache.scaling.equals(this.scaling))
  16455. return false;
  16456. return true;
  16457. };
  16458. TransformNode.prototype._initCache = function () {
  16459. _super.prototype._initCache.call(this);
  16460. this._cache.localMatrixUpdated = false;
  16461. this._cache.position = BABYLON.Vector3.Zero();
  16462. this._cache.scaling = BABYLON.Vector3.Zero();
  16463. this._cache.rotation = BABYLON.Vector3.Zero();
  16464. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16465. this._cache.billboardMode = -1;
  16466. };
  16467. TransformNode.prototype.markAsDirty = function (property) {
  16468. if (property === "rotation") {
  16469. this.rotationQuaternion = null;
  16470. }
  16471. this._currentRenderId = Number.MAX_VALUE;
  16472. this._isDirty = true;
  16473. return this;
  16474. };
  16475. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16476. /**
  16477. * Returns the current mesh absolute position.
  16478. * Retuns a Vector3.
  16479. */
  16480. get: function () {
  16481. return this._absolutePosition;
  16482. },
  16483. enumerable: true,
  16484. configurable: true
  16485. });
  16486. /**
  16487. * Sets a new matrix to apply before all other transformation
  16488. * @param matrix defines the transform matrix
  16489. * @returns the current TransformNode
  16490. */
  16491. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16492. return this.setPivotMatrix(matrix, false);
  16493. };
  16494. /**
  16495. * Sets a new pivot matrix to the current node
  16496. * @param matrix defines the new pivot matrix to use
  16497. * @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
  16498. * @returns the current TransformNode
  16499. */
  16500. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16501. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16502. this._pivotMatrix = matrix.clone();
  16503. this._cache.pivotMatrixUpdated = true;
  16504. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16505. if (this._postMultiplyPivotMatrix) {
  16506. if (!this._pivotMatrixInverse) {
  16507. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16508. }
  16509. else {
  16510. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16511. }
  16512. }
  16513. return this;
  16514. };
  16515. /**
  16516. * Returns the mesh pivot matrix.
  16517. * Default : Identity.
  16518. * A Matrix is returned.
  16519. */
  16520. TransformNode.prototype.getPivotMatrix = function () {
  16521. return this._pivotMatrix;
  16522. };
  16523. /**
  16524. * Prevents the World matrix to be computed any longer.
  16525. * Returns the AbstractMesh.
  16526. */
  16527. TransformNode.prototype.freezeWorldMatrix = function () {
  16528. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16529. this.computeWorldMatrix(true);
  16530. this._isWorldMatrixFrozen = true;
  16531. return this;
  16532. };
  16533. /**
  16534. * Allows back the World matrix computation.
  16535. * Returns the AbstractMesh.
  16536. */
  16537. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16538. this._isWorldMatrixFrozen = false;
  16539. this.computeWorldMatrix(true);
  16540. return this;
  16541. };
  16542. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16543. /**
  16544. * True if the World matrix has been frozen.
  16545. * Returns a boolean.
  16546. */
  16547. get: function () {
  16548. return this._isWorldMatrixFrozen;
  16549. },
  16550. enumerable: true,
  16551. configurable: true
  16552. });
  16553. /**
  16554. * Retuns the mesh absolute position in the World.
  16555. * Returns a Vector3.
  16556. */
  16557. TransformNode.prototype.getAbsolutePosition = function () {
  16558. this.computeWorldMatrix();
  16559. return this._absolutePosition;
  16560. };
  16561. /**
  16562. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16563. * Returns the AbstractMesh.
  16564. */
  16565. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16566. if (!absolutePosition) {
  16567. return this;
  16568. }
  16569. var absolutePositionX;
  16570. var absolutePositionY;
  16571. var absolutePositionZ;
  16572. if (absolutePosition.x === undefined) {
  16573. if (arguments.length < 3) {
  16574. return this;
  16575. }
  16576. absolutePositionX = arguments[0];
  16577. absolutePositionY = arguments[1];
  16578. absolutePositionZ = arguments[2];
  16579. }
  16580. else {
  16581. absolutePositionX = absolutePosition.x;
  16582. absolutePositionY = absolutePosition.y;
  16583. absolutePositionZ = absolutePosition.z;
  16584. }
  16585. if (this.parent) {
  16586. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16587. invertParentWorldMatrix.invert();
  16588. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16589. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16590. }
  16591. else {
  16592. this.position.x = absolutePositionX;
  16593. this.position.y = absolutePositionY;
  16594. this.position.z = absolutePositionZ;
  16595. }
  16596. return this;
  16597. };
  16598. /**
  16599. * Sets the mesh position in its local space.
  16600. * Returns the AbstractMesh.
  16601. */
  16602. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16603. this.computeWorldMatrix();
  16604. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16605. return this;
  16606. };
  16607. /**
  16608. * Returns the mesh position in the local space from the current World matrix values.
  16609. * Returns a new Vector3.
  16610. */
  16611. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16612. this.computeWorldMatrix();
  16613. var invLocalWorldMatrix = this._localWorld.clone();
  16614. invLocalWorldMatrix.invert();
  16615. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16616. };
  16617. /**
  16618. * Translates the mesh along the passed Vector3 in its local space.
  16619. * Returns the AbstractMesh.
  16620. */
  16621. TransformNode.prototype.locallyTranslate = function (vector3) {
  16622. this.computeWorldMatrix(true);
  16623. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16624. return this;
  16625. };
  16626. /**
  16627. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16628. * @param targetPoint the position (must be in same space as current mesh) to look at
  16629. * @param yawCor optional yaw (y-axis) correction in radians
  16630. * @param pitchCor optional pitch (x-axis) correction in radians
  16631. * @param rollCor optional roll (z-axis) correction in radians
  16632. * @param space the choosen space of the target
  16633. * @returns the TransformNode.
  16634. */
  16635. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16636. if (yawCor === void 0) { yawCor = 0; }
  16637. if (pitchCor === void 0) { pitchCor = 0; }
  16638. if (rollCor === void 0) { rollCor = 0; }
  16639. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16640. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16641. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16642. targetPoint.subtractToRef(pos, dv);
  16643. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16644. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16645. var pitch = Math.atan2(dv.y, len);
  16646. if (this.rotationQuaternion) {
  16647. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16648. }
  16649. else {
  16650. this.rotation.x = pitch + pitchCor;
  16651. this.rotation.y = yaw + yawCor;
  16652. this.rotation.z = rollCor;
  16653. }
  16654. return this;
  16655. };
  16656. /**
  16657. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16658. * This Vector3 is expressed in the World space.
  16659. */
  16660. TransformNode.prototype.getDirection = function (localAxis) {
  16661. var result = BABYLON.Vector3.Zero();
  16662. this.getDirectionToRef(localAxis, result);
  16663. return result;
  16664. };
  16665. /**
  16666. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16667. * localAxis is expressed in the mesh local space.
  16668. * result is computed in the Wordl space from the mesh World matrix.
  16669. * Returns the AbstractMesh.
  16670. */
  16671. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16672. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16673. return this;
  16674. };
  16675. /**
  16676. * Sets a new pivot point to the current node
  16677. * @param point defines the new pivot point to use
  16678. * @param space defines if the point is in world or local space (local by default)
  16679. * @returns the current TransformNode
  16680. */
  16681. TransformNode.prototype.setPivotPoint = function (point, space) {
  16682. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16683. if (this.getScene().getRenderId() == 0) {
  16684. this.computeWorldMatrix(true);
  16685. }
  16686. var wm = this.getWorldMatrix();
  16687. if (space == BABYLON.Space.WORLD) {
  16688. var tmat = BABYLON.Tmp.Matrix[0];
  16689. wm.invertToRef(tmat);
  16690. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16691. }
  16692. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16693. };
  16694. /**
  16695. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16696. */
  16697. TransformNode.prototype.getPivotPoint = function () {
  16698. var point = BABYLON.Vector3.Zero();
  16699. this.getPivotPointToRef(point);
  16700. return point;
  16701. };
  16702. /**
  16703. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16704. * Returns the AbstractMesh.
  16705. */
  16706. TransformNode.prototype.getPivotPointToRef = function (result) {
  16707. result.x = -this._pivotMatrix.m[12];
  16708. result.y = -this._pivotMatrix.m[13];
  16709. result.z = -this._pivotMatrix.m[14];
  16710. return this;
  16711. };
  16712. /**
  16713. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16714. */
  16715. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16716. var point = BABYLON.Vector3.Zero();
  16717. this.getAbsolutePivotPointToRef(point);
  16718. return point;
  16719. };
  16720. /**
  16721. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16722. * Returns the AbstractMesh.
  16723. */
  16724. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16725. result.x = this._pivotMatrix.m[12];
  16726. result.y = this._pivotMatrix.m[13];
  16727. result.z = this._pivotMatrix.m[14];
  16728. this.getPivotPointToRef(result);
  16729. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16730. return this;
  16731. };
  16732. /**
  16733. * Defines the passed node as the parent of the current node.
  16734. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16735. * Returns the TransformNode.
  16736. */
  16737. TransformNode.prototype.setParent = function (node) {
  16738. if (node === null) {
  16739. var rotation = BABYLON.Tmp.Quaternion[0];
  16740. var position = BABYLON.Tmp.Vector3[0];
  16741. var scale = BABYLON.Tmp.Vector3[1];
  16742. if (this.parent && this.parent.computeWorldMatrix) {
  16743. this.parent.computeWorldMatrix(true);
  16744. }
  16745. this.computeWorldMatrix(true);
  16746. this.getWorldMatrix().decompose(scale, rotation, position);
  16747. if (this.rotationQuaternion) {
  16748. this.rotationQuaternion.copyFrom(rotation);
  16749. }
  16750. else {
  16751. rotation.toEulerAnglesToRef(this.rotation);
  16752. }
  16753. this.scaling.x = scale.x;
  16754. this.scaling.y = scale.y;
  16755. this.scaling.z = scale.z;
  16756. this.position.x = position.x;
  16757. this.position.y = position.y;
  16758. this.position.z = position.z;
  16759. }
  16760. else {
  16761. var rotation = BABYLON.Tmp.Quaternion[0];
  16762. var position = BABYLON.Tmp.Vector3[0];
  16763. var scale = BABYLON.Tmp.Vector3[1];
  16764. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16765. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16766. this.computeWorldMatrix(true);
  16767. node.computeWorldMatrix(true);
  16768. node.getWorldMatrix().invertToRef(invParentMatrix);
  16769. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16770. diffMatrix.decompose(scale, rotation, position);
  16771. if (this.rotationQuaternion) {
  16772. this.rotationQuaternion.copyFrom(rotation);
  16773. }
  16774. else {
  16775. rotation.toEulerAnglesToRef(this.rotation);
  16776. }
  16777. this.position.x = position.x;
  16778. this.position.y = position.y;
  16779. this.position.z = position.z;
  16780. this.scaling.x = scale.x;
  16781. this.scaling.y = scale.y;
  16782. this.scaling.z = scale.z;
  16783. }
  16784. this.parent = node;
  16785. return this;
  16786. };
  16787. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16788. get: function () {
  16789. return this._nonUniformScaling;
  16790. },
  16791. enumerable: true,
  16792. configurable: true
  16793. });
  16794. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16795. if (this._nonUniformScaling === value) {
  16796. return false;
  16797. }
  16798. this._nonUniformScaling = true;
  16799. return true;
  16800. };
  16801. /**
  16802. * Attach the current TransformNode to another TransformNode associated with a bone
  16803. * @param bone Bone affecting the TransformNode
  16804. * @param affectedTransformNode TransformNode associated with the bone
  16805. */
  16806. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16807. this._transformToBoneReferal = affectedTransformNode;
  16808. this.parent = bone;
  16809. if (bone.getWorldMatrix().determinant() < 0) {
  16810. this.scalingDeterminant *= -1;
  16811. }
  16812. return this;
  16813. };
  16814. TransformNode.prototype.detachFromBone = function () {
  16815. if (!this.parent) {
  16816. return this;
  16817. }
  16818. if (this.parent.getWorldMatrix().determinant() < 0) {
  16819. this.scalingDeterminant *= -1;
  16820. }
  16821. this._transformToBoneReferal = null;
  16822. this.parent = null;
  16823. return this;
  16824. };
  16825. /**
  16826. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16827. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16828. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16829. * The passed axis is also normalized.
  16830. * Returns the AbstractMesh.
  16831. */
  16832. TransformNode.prototype.rotate = function (axis, amount, space) {
  16833. axis.normalize();
  16834. if (!this.rotationQuaternion) {
  16835. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16836. this.rotation = BABYLON.Vector3.Zero();
  16837. }
  16838. var rotationQuaternion;
  16839. if (!space || space === BABYLON.Space.LOCAL) {
  16840. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16841. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16842. }
  16843. else {
  16844. if (this.parent) {
  16845. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16846. invertParentWorldMatrix.invert();
  16847. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16848. }
  16849. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16850. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16851. }
  16852. return this;
  16853. };
  16854. /**
  16855. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16856. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16857. * The passed axis is also normalized.
  16858. * Returns the AbstractMesh.
  16859. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16860. */
  16861. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16862. axis.normalize();
  16863. if (!this.rotationQuaternion) {
  16864. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16865. this.rotation.copyFromFloats(0, 0, 0);
  16866. }
  16867. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16868. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16869. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16870. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16871. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16872. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16873. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16874. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16875. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16876. return this;
  16877. };
  16878. /**
  16879. * Translates the mesh along the axis vector for the passed distance in the given space.
  16880. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16881. * Returns the AbstractMesh.
  16882. */
  16883. TransformNode.prototype.translate = function (axis, distance, space) {
  16884. var displacementVector = axis.scale(distance);
  16885. if (!space || space === BABYLON.Space.LOCAL) {
  16886. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16887. this.setPositionWithLocalVector(tempV3);
  16888. }
  16889. else {
  16890. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16891. }
  16892. return this;
  16893. };
  16894. /**
  16895. * Adds a rotation step to the mesh current rotation.
  16896. * x, y, z are Euler angles expressed in radians.
  16897. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16898. * This means this rotation is made in the mesh local space only.
  16899. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16900. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16901. * ```javascript
  16902. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16903. * ```
  16904. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16905. * 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.
  16906. * Returns the AbstractMesh.
  16907. */
  16908. TransformNode.prototype.addRotation = function (x, y, z) {
  16909. var rotationQuaternion;
  16910. if (this.rotationQuaternion) {
  16911. rotationQuaternion = this.rotationQuaternion;
  16912. }
  16913. else {
  16914. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16915. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16916. }
  16917. var accumulation = BABYLON.Tmp.Quaternion[0];
  16918. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16919. rotationQuaternion.multiplyInPlace(accumulation);
  16920. if (!this.rotationQuaternion) {
  16921. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16922. }
  16923. return this;
  16924. };
  16925. /**
  16926. * Computes the mesh World matrix and returns it.
  16927. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16928. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16929. * If the parameter `force`is set to `true`, the actual computation is done.
  16930. * Returns the mesh World Matrix.
  16931. */
  16932. TransformNode.prototype.computeWorldMatrix = function (force) {
  16933. if (this._isWorldMatrixFrozen) {
  16934. return this._worldMatrix;
  16935. }
  16936. if (!force && this.isSynchronized(true)) {
  16937. return this._worldMatrix;
  16938. }
  16939. this._cache.position.copyFrom(this.position);
  16940. this._cache.scaling.copyFrom(this.scaling);
  16941. this._cache.pivotMatrixUpdated = false;
  16942. this._cache.billboardMode = this.billboardMode;
  16943. this._currentRenderId = this.getScene().getRenderId();
  16944. this._isDirty = false;
  16945. // Scaling
  16946. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16947. // Rotation
  16948. //rotate, if quaternion is set and rotation was used
  16949. if (this.rotationQuaternion) {
  16950. var len = this.rotation.length();
  16951. if (len) {
  16952. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16953. this.rotation.copyFromFloats(0, 0, 0);
  16954. }
  16955. }
  16956. if (this.rotationQuaternion) {
  16957. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16958. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16959. }
  16960. else {
  16961. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16962. this._cache.rotation.copyFrom(this.rotation);
  16963. }
  16964. // Translation
  16965. var camera = this.getScene().activeCamera;
  16966. if (this.infiniteDistance && !this.parent && camera) {
  16967. var cameraWorldMatrix = camera.getWorldMatrix();
  16968. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16969. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16970. }
  16971. else {
  16972. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16973. }
  16974. // Composing transformations
  16975. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16976. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16977. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16978. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16979. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16980. // Need to decompose each rotation here
  16981. var currentPosition = BABYLON.Tmp.Vector3[3];
  16982. if (this.parent && this.parent.getWorldMatrix) {
  16983. if (this._transformToBoneReferal) {
  16984. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16985. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16986. }
  16987. else {
  16988. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16989. }
  16990. }
  16991. else {
  16992. currentPosition.copyFrom(this.position);
  16993. }
  16994. currentPosition.subtractInPlace(camera.globalPosition);
  16995. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16996. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16997. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16998. }
  16999. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17000. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17001. }
  17002. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17003. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17004. }
  17005. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17006. }
  17007. else {
  17008. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17009. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17010. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17011. }
  17012. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17013. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17014. }
  17015. // Local world
  17016. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17017. // Parent
  17018. if (this.parent && this.parent.getWorldMatrix) {
  17019. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17020. if (this._transformToBoneReferal) {
  17021. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17022. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17023. }
  17024. else {
  17025. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17026. }
  17027. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17028. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17029. this._worldMatrix.copyFrom(this._localWorld);
  17030. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17031. }
  17032. else {
  17033. if (this._transformToBoneReferal) {
  17034. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17035. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17036. }
  17037. else {
  17038. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17039. }
  17040. }
  17041. this._markSyncedWithParent();
  17042. }
  17043. else {
  17044. this._worldMatrix.copyFrom(this._localWorld);
  17045. }
  17046. // Post multiply inverse of pivotMatrix
  17047. if (this._postMultiplyPivotMatrix) {
  17048. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17049. }
  17050. // Normal matrix
  17051. if (this.scaling.isNonUniform) {
  17052. this._updateNonUniformScalingState(true);
  17053. }
  17054. else if (this.parent && this.parent._nonUniformScaling) {
  17055. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17056. }
  17057. else {
  17058. this._updateNonUniformScalingState(false);
  17059. }
  17060. this._afterComputeWorldMatrix();
  17061. // Absolute position
  17062. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17063. // Callbacks
  17064. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17065. if (!this._poseMatrix) {
  17066. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17067. }
  17068. // Cache the determinant
  17069. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17070. return this._worldMatrix;
  17071. };
  17072. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17073. };
  17074. /**
  17075. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17076. * @param func: callback function to add
  17077. *
  17078. * Returns the TransformNode.
  17079. */
  17080. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17081. this.onAfterWorldMatrixUpdateObservable.add(func);
  17082. return this;
  17083. };
  17084. /**
  17085. * Removes a registered callback function.
  17086. * Returns the TransformNode.
  17087. */
  17088. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17089. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17090. return this;
  17091. };
  17092. /**
  17093. * Clone the current transform node
  17094. * Returns the new transform node
  17095. * @param name Name of the new clone
  17096. * @param newParent New parent for the clone
  17097. * @param doNotCloneChildren Do not clone children hierarchy
  17098. */
  17099. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17100. var _this = this;
  17101. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17102. result.name = name;
  17103. result.id = name;
  17104. if (newParent) {
  17105. result.parent = newParent;
  17106. }
  17107. if (!doNotCloneChildren) {
  17108. // Children
  17109. var directDescendants = this.getDescendants(true);
  17110. for (var index = 0; index < directDescendants.length; index++) {
  17111. var child = directDescendants[index];
  17112. if (child.clone) {
  17113. child.clone(name + "." + child.name, result);
  17114. }
  17115. }
  17116. }
  17117. return result;
  17118. };
  17119. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17120. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17121. serializationObject.type = this.getClassName();
  17122. // Parent
  17123. if (this.parent) {
  17124. serializationObject.parentId = this.parent.id;
  17125. }
  17126. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17127. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17128. }
  17129. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17130. serializationObject.isEnabled = this.isEnabled();
  17131. // Parent
  17132. if (this.parent) {
  17133. serializationObject.parentId = this.parent.id;
  17134. }
  17135. return serializationObject;
  17136. };
  17137. // Statics
  17138. /**
  17139. * Returns a new TransformNode object parsed from the source provided.
  17140. * The parameter `parsedMesh` is the source.
  17141. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17142. */
  17143. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17144. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17145. if (BABYLON.Tags) {
  17146. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17147. }
  17148. if (parsedTransformNode.localMatrix) {
  17149. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17150. }
  17151. else if (parsedTransformNode.pivotMatrix) {
  17152. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17153. }
  17154. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17155. // Parent
  17156. if (parsedTransformNode.parentId) {
  17157. transformNode._waitingParentId = parsedTransformNode.parentId;
  17158. }
  17159. return transformNode;
  17160. };
  17161. /**
  17162. * Releases resources associated with this transform node.
  17163. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17164. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17165. */
  17166. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17167. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17168. // Animations
  17169. this.getScene().stopAnimation(this);
  17170. // Remove from scene
  17171. this.getScene().removeTransformNode(this);
  17172. this.onAfterWorldMatrixUpdateObservable.clear();
  17173. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17174. };
  17175. // Statics
  17176. TransformNode.BILLBOARDMODE_NONE = 0;
  17177. TransformNode.BILLBOARDMODE_X = 1;
  17178. TransformNode.BILLBOARDMODE_Y = 2;
  17179. TransformNode.BILLBOARDMODE_Z = 4;
  17180. TransformNode.BILLBOARDMODE_ALL = 7;
  17181. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17182. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17183. __decorate([
  17184. BABYLON.serializeAsVector3()
  17185. ], TransformNode.prototype, "_rotation", void 0);
  17186. __decorate([
  17187. BABYLON.serializeAsQuaternion()
  17188. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17189. __decorate([
  17190. BABYLON.serializeAsVector3()
  17191. ], TransformNode.prototype, "_scaling", void 0);
  17192. __decorate([
  17193. BABYLON.serialize()
  17194. ], TransformNode.prototype, "billboardMode", void 0);
  17195. __decorate([
  17196. BABYLON.serialize()
  17197. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17198. __decorate([
  17199. BABYLON.serialize()
  17200. ], TransformNode.prototype, "infiniteDistance", void 0);
  17201. __decorate([
  17202. BABYLON.serializeAsVector3()
  17203. ], TransformNode.prototype, "position", void 0);
  17204. return TransformNode;
  17205. }(BABYLON.Node));
  17206. BABYLON.TransformNode = TransformNode;
  17207. })(BABYLON || (BABYLON = {}));
  17208. //# sourceMappingURL=babylon.transformNode.js.map
  17209. var BABYLON;
  17210. (function (BABYLON) {
  17211. var AbstractMesh = /** @class */ (function (_super) {
  17212. __extends(AbstractMesh, _super);
  17213. // Constructor
  17214. function AbstractMesh(name, scene) {
  17215. if (scene === void 0) { scene = null; }
  17216. var _this = _super.call(this, name, scene, false) || this;
  17217. _this._facetNb = 0; // facet number
  17218. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17219. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17220. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17221. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17222. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17223. _this._subDiv = {
  17224. max: 1,
  17225. X: 1,
  17226. Y: 1,
  17227. Z: 1
  17228. };
  17229. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17230. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17231. // Events
  17232. /**
  17233. * An event triggered when this mesh collides with another one
  17234. * @type {BABYLON.Observable}
  17235. */
  17236. _this.onCollideObservable = new BABYLON.Observable();
  17237. /**
  17238. * An event triggered when the collision's position changes
  17239. * @type {BABYLON.Observable}
  17240. */
  17241. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17242. /**
  17243. * An event triggered when material is changed
  17244. * @type {BABYLON.Observable}
  17245. */
  17246. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17247. // Properties
  17248. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17249. /**
  17250. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17251. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17252. * or
  17253. * 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.
  17254. * for more info check WebGl documentations
  17255. */
  17256. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17257. /**
  17258. * 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:
  17259. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17260. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17261. * 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.
  17262. */
  17263. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17264. /**
  17265. * 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.
  17266. * The default value is -1 which means don't break the query and wait till the result.
  17267. */
  17268. _this.occlusionRetryCount = -1;
  17269. _this._occlusionInternalRetryCounter = 0;
  17270. _this._isOccluded = false;
  17271. _this._isOcclusionQueryInProgress = false;
  17272. _this._visibility = 1.0;
  17273. _this.alphaIndex = Number.MAX_VALUE;
  17274. _this.isVisible = true;
  17275. _this.isPickable = true;
  17276. _this.showBoundingBox = false;
  17277. _this.showSubMeshesBoundingBox = false;
  17278. _this.isBlocker = false;
  17279. _this.enablePointerMoveEvents = false;
  17280. _this.renderingGroupId = 0;
  17281. _this._receiveShadows = false;
  17282. _this.renderOutline = false;
  17283. _this.outlineColor = BABYLON.Color3.Red();
  17284. _this.outlineWidth = 0.02;
  17285. _this.renderOverlay = false;
  17286. _this.overlayColor = BABYLON.Color3.Red();
  17287. _this.overlayAlpha = 0.5;
  17288. _this._hasVertexAlpha = false;
  17289. _this._useVertexColors = true;
  17290. _this._computeBonesUsingShaders = true;
  17291. _this._numBoneInfluencers = 4;
  17292. _this._applyFog = true;
  17293. _this.useOctreeForRenderingSelection = true;
  17294. _this.useOctreeForPicking = true;
  17295. _this.useOctreeForCollisions = true;
  17296. _this._layerMask = 0x0FFFFFFF;
  17297. /**
  17298. * True if the mesh must be rendered in any case.
  17299. */
  17300. _this.alwaysSelectAsActiveMesh = false;
  17301. /**
  17302. * This scene's action manager
  17303. * @type {BABYLON.ActionManager}
  17304. */
  17305. _this.actionManager = null;
  17306. // Physics
  17307. _this.physicsImpostor = null;
  17308. // Collisions
  17309. _this._checkCollisions = false;
  17310. _this._collisionMask = -1;
  17311. _this._collisionGroup = -1;
  17312. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17313. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17314. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17315. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17316. // Edges
  17317. _this.edgesWidth = 1;
  17318. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17319. // Cache
  17320. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17321. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17322. _this._renderId = 0;
  17323. _this._intersectionsInProgress = new Array();
  17324. _this._unIndexed = false;
  17325. _this._lightSources = new Array();
  17326. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17327. if (collidedMesh === void 0) { collidedMesh = null; }
  17328. //TODO move this to the collision coordinator!
  17329. if (_this.getScene().workerCollisions)
  17330. newPosition.multiplyInPlace(_this._collider._radius);
  17331. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17332. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17333. _this.position.addInPlace(_this._diffPositionForCollisions);
  17334. }
  17335. if (collidedMesh) {
  17336. _this.onCollideObservable.notifyObservers(collidedMesh);
  17337. }
  17338. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17339. };
  17340. _this.getScene().addMesh(_this);
  17341. _this._resyncLightSources();
  17342. return _this;
  17343. }
  17344. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17345. get: function () {
  17346. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17347. },
  17348. enumerable: true,
  17349. configurable: true
  17350. });
  17351. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17352. get: function () {
  17353. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17354. },
  17355. enumerable: true,
  17356. configurable: true
  17357. });
  17358. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17359. get: function () {
  17360. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17361. },
  17362. enumerable: true,
  17363. configurable: true
  17364. });
  17365. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17366. get: function () {
  17367. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17368. },
  17369. enumerable: true,
  17370. configurable: true
  17371. });
  17372. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17373. get: function () {
  17374. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17375. },
  17376. enumerable: true,
  17377. configurable: true
  17378. });
  17379. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17380. /**
  17381. * Read-only : the number of facets in the mesh
  17382. */
  17383. get: function () {
  17384. return this._facetNb;
  17385. },
  17386. enumerable: true,
  17387. configurable: true
  17388. });
  17389. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17390. /**
  17391. * The number (integer) of subdivisions per axis in the partioning space
  17392. */
  17393. get: function () {
  17394. return this._partitioningSubdivisions;
  17395. },
  17396. set: function (nb) {
  17397. this._partitioningSubdivisions = nb;
  17398. },
  17399. enumerable: true,
  17400. configurable: true
  17401. });
  17402. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17403. /**
  17404. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17405. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17406. */
  17407. get: function () {
  17408. return this._partitioningBBoxRatio;
  17409. },
  17410. set: function (ratio) {
  17411. this._partitioningBBoxRatio = ratio;
  17412. },
  17413. enumerable: true,
  17414. configurable: true
  17415. });
  17416. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17417. /**
  17418. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17419. * Works only for updatable meshes.
  17420. * Doesn't work with multi-materials.
  17421. */
  17422. get: function () {
  17423. return this._facetDepthSort;
  17424. },
  17425. set: function (sort) {
  17426. this._facetDepthSort = sort;
  17427. },
  17428. enumerable: true,
  17429. configurable: true
  17430. });
  17431. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17432. /**
  17433. * The location (Vector3) where the facet depth sort must be computed from.
  17434. * By default, the active camera position.
  17435. * Used only when facet depth sort is enabled.
  17436. */
  17437. get: function () {
  17438. return this._facetDepthSortFrom;
  17439. },
  17440. set: function (location) {
  17441. this._facetDepthSortFrom = location;
  17442. },
  17443. enumerable: true,
  17444. configurable: true
  17445. });
  17446. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17447. /**
  17448. * Read-only boolean : is the feature facetData enabled ?
  17449. */
  17450. get: function () {
  17451. return this._facetDataEnabled;
  17452. },
  17453. enumerable: true,
  17454. configurable: true
  17455. });
  17456. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17457. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17458. return false;
  17459. }
  17460. this._markSubMeshesAsMiscDirty();
  17461. return true;
  17462. };
  17463. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17464. set: function (callback) {
  17465. if (this._onCollideObserver) {
  17466. this.onCollideObservable.remove(this._onCollideObserver);
  17467. }
  17468. this._onCollideObserver = this.onCollideObservable.add(callback);
  17469. },
  17470. enumerable: true,
  17471. configurable: true
  17472. });
  17473. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17474. set: function (callback) {
  17475. if (this._onCollisionPositionChangeObserver) {
  17476. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17477. }
  17478. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17479. },
  17480. enumerable: true,
  17481. configurable: true
  17482. });
  17483. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17484. /**
  17485. * 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.
  17486. */
  17487. get: function () {
  17488. return this._isOccluded;
  17489. },
  17490. set: function (value) {
  17491. this._isOccluded = value;
  17492. },
  17493. enumerable: true,
  17494. configurable: true
  17495. });
  17496. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17497. /**
  17498. * Flag to check the progress status of the query
  17499. */
  17500. get: function () {
  17501. return this._isOcclusionQueryInProgress;
  17502. },
  17503. enumerable: true,
  17504. configurable: true
  17505. });
  17506. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17507. /**
  17508. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17509. */
  17510. get: function () {
  17511. return this._visibility;
  17512. },
  17513. /**
  17514. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17515. */
  17516. set: function (value) {
  17517. if (this._visibility === value) {
  17518. return;
  17519. }
  17520. this._visibility = value;
  17521. this._markSubMeshesAsMiscDirty();
  17522. },
  17523. enumerable: true,
  17524. configurable: true
  17525. });
  17526. Object.defineProperty(AbstractMesh.prototype, "material", {
  17527. get: function () {
  17528. return this._material;
  17529. },
  17530. set: function (value) {
  17531. if (this._material === value) {
  17532. return;
  17533. }
  17534. this._material = value;
  17535. if (this.onMaterialChangedObservable.hasObservers) {
  17536. this.onMaterialChangedObservable.notifyObservers(this);
  17537. }
  17538. if (!this.subMeshes) {
  17539. return;
  17540. }
  17541. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17542. var subMesh = _a[_i];
  17543. subMesh.setEffect(null);
  17544. }
  17545. },
  17546. enumerable: true,
  17547. configurable: true
  17548. });
  17549. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17550. get: function () {
  17551. return this._receiveShadows;
  17552. },
  17553. set: function (value) {
  17554. if (this._receiveShadows === value) {
  17555. return;
  17556. }
  17557. this._receiveShadows = value;
  17558. this._markSubMeshesAsLightDirty();
  17559. },
  17560. enumerable: true,
  17561. configurable: true
  17562. });
  17563. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17564. get: function () {
  17565. return this._hasVertexAlpha;
  17566. },
  17567. set: function (value) {
  17568. if (this._hasVertexAlpha === value) {
  17569. return;
  17570. }
  17571. this._hasVertexAlpha = value;
  17572. this._markSubMeshesAsAttributesDirty();
  17573. this._markSubMeshesAsMiscDirty();
  17574. },
  17575. enumerable: true,
  17576. configurable: true
  17577. });
  17578. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17579. get: function () {
  17580. return this._useVertexColors;
  17581. },
  17582. set: function (value) {
  17583. if (this._useVertexColors === value) {
  17584. return;
  17585. }
  17586. this._useVertexColors = value;
  17587. this._markSubMeshesAsAttributesDirty();
  17588. },
  17589. enumerable: true,
  17590. configurable: true
  17591. });
  17592. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17593. get: function () {
  17594. return this._computeBonesUsingShaders;
  17595. },
  17596. set: function (value) {
  17597. if (this._computeBonesUsingShaders === value) {
  17598. return;
  17599. }
  17600. this._computeBonesUsingShaders = value;
  17601. this._markSubMeshesAsAttributesDirty();
  17602. },
  17603. enumerable: true,
  17604. configurable: true
  17605. });
  17606. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17607. get: function () {
  17608. return this._numBoneInfluencers;
  17609. },
  17610. set: function (value) {
  17611. if (this._numBoneInfluencers === value) {
  17612. return;
  17613. }
  17614. this._numBoneInfluencers = value;
  17615. this._markSubMeshesAsAttributesDirty();
  17616. },
  17617. enumerable: true,
  17618. configurable: true
  17619. });
  17620. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17621. get: function () {
  17622. return this._applyFog;
  17623. },
  17624. set: function (value) {
  17625. if (this._applyFog === value) {
  17626. return;
  17627. }
  17628. this._applyFog = value;
  17629. this._markSubMeshesAsMiscDirty();
  17630. },
  17631. enumerable: true,
  17632. configurable: true
  17633. });
  17634. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17635. get: function () {
  17636. return this._layerMask;
  17637. },
  17638. set: function (value) {
  17639. if (value === this._layerMask) {
  17640. return;
  17641. }
  17642. this._layerMask = value;
  17643. this._resyncLightSources();
  17644. },
  17645. enumerable: true,
  17646. configurable: true
  17647. });
  17648. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17649. get: function () {
  17650. return this._collisionMask;
  17651. },
  17652. set: function (mask) {
  17653. this._collisionMask = !isNaN(mask) ? mask : -1;
  17654. },
  17655. enumerable: true,
  17656. configurable: true
  17657. });
  17658. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17659. get: function () {
  17660. return this._collisionGroup;
  17661. },
  17662. set: function (mask) {
  17663. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17664. },
  17665. enumerable: true,
  17666. configurable: true
  17667. });
  17668. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17669. get: function () {
  17670. return null;
  17671. },
  17672. enumerable: true,
  17673. configurable: true
  17674. });
  17675. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17676. get: function () {
  17677. return this._skeleton;
  17678. },
  17679. set: function (value) {
  17680. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17681. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17682. }
  17683. if (value && value.needInitialSkinMatrix) {
  17684. value._registerMeshWithPoseMatrix(this);
  17685. }
  17686. this._skeleton = value;
  17687. if (!this._skeleton) {
  17688. this._bonesTransformMatrices = null;
  17689. }
  17690. this._markSubMeshesAsAttributesDirty();
  17691. },
  17692. enumerable: true,
  17693. configurable: true
  17694. });
  17695. /**
  17696. * Returns the string "AbstractMesh"
  17697. */
  17698. AbstractMesh.prototype.getClassName = function () {
  17699. return "AbstractMesh";
  17700. };
  17701. /**
  17702. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17703. */
  17704. AbstractMesh.prototype.toString = function (fullDetails) {
  17705. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17706. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17707. if (this._skeleton) {
  17708. ret += ", skeleton: " + this._skeleton.name;
  17709. }
  17710. if (fullDetails) {
  17711. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17712. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17713. }
  17714. return ret;
  17715. };
  17716. AbstractMesh.prototype._rebuild = function () {
  17717. if (this._occlusionQuery) {
  17718. this._occlusionQuery = null;
  17719. }
  17720. if (this._edgesRenderer) {
  17721. this._edgesRenderer._rebuild();
  17722. }
  17723. if (!this.subMeshes) {
  17724. return;
  17725. }
  17726. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17727. var subMesh = _a[_i];
  17728. subMesh._rebuild();
  17729. }
  17730. };
  17731. AbstractMesh.prototype._resyncLightSources = function () {
  17732. this._lightSources.length = 0;
  17733. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17734. var light = _a[_i];
  17735. if (!light.isEnabled()) {
  17736. continue;
  17737. }
  17738. if (light.canAffectMesh(this)) {
  17739. this._lightSources.push(light);
  17740. }
  17741. }
  17742. this._markSubMeshesAsLightDirty();
  17743. };
  17744. AbstractMesh.prototype._resyncLighSource = function (light) {
  17745. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17746. var index = this._lightSources.indexOf(light);
  17747. if (index === -1) {
  17748. if (!isIn) {
  17749. return;
  17750. }
  17751. this._lightSources.push(light);
  17752. }
  17753. else {
  17754. if (isIn) {
  17755. return;
  17756. }
  17757. this._lightSources.splice(index, 1);
  17758. }
  17759. this._markSubMeshesAsLightDirty();
  17760. };
  17761. AbstractMesh.prototype._removeLightSource = function (light) {
  17762. var index = this._lightSources.indexOf(light);
  17763. if (index === -1) {
  17764. return;
  17765. }
  17766. this._lightSources.splice(index, 1);
  17767. this._markSubMeshesAsLightDirty();
  17768. };
  17769. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17770. if (!this.subMeshes) {
  17771. return;
  17772. }
  17773. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17774. var subMesh = _a[_i];
  17775. if (subMesh._materialDefines) {
  17776. func(subMesh._materialDefines);
  17777. }
  17778. }
  17779. };
  17780. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17781. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17782. };
  17783. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17784. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17785. };
  17786. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17787. if (!this.subMeshes) {
  17788. return;
  17789. }
  17790. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17791. var subMesh = _a[_i];
  17792. var material = subMesh.getMaterial();
  17793. if (material) {
  17794. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17795. }
  17796. }
  17797. };
  17798. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17799. /**
  17800. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17801. * Default : (1.0, 1.0, 1.0)
  17802. */
  17803. get: function () {
  17804. return this._scaling;
  17805. },
  17806. /**
  17807. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17808. * Default : (1.0, 1.0, 1.0)
  17809. */
  17810. set: function (newScaling) {
  17811. this._scaling = newScaling;
  17812. if (this.physicsImpostor) {
  17813. this.physicsImpostor.forceUpdate();
  17814. }
  17815. },
  17816. enumerable: true,
  17817. configurable: true
  17818. });
  17819. // Methods
  17820. /**
  17821. * Disables the mesh edger rendering mode.
  17822. * Returns the AbstractMesh.
  17823. */
  17824. AbstractMesh.prototype.disableEdgesRendering = function () {
  17825. if (this._edgesRenderer) {
  17826. this._edgesRenderer.dispose();
  17827. this._edgesRenderer = null;
  17828. }
  17829. return this;
  17830. };
  17831. /**
  17832. * Enables the edge rendering mode on the mesh.
  17833. * This mode makes the mesh edges visible.
  17834. * Returns the AbstractMesh.
  17835. */
  17836. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17837. if (epsilon === void 0) { epsilon = 0.95; }
  17838. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17839. this.disableEdgesRendering();
  17840. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17841. return this;
  17842. };
  17843. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17844. /**
  17845. * Returns true if the mesh is blocked. Used by the class Mesh.
  17846. * Returns the boolean `false` by default.
  17847. */
  17848. get: function () {
  17849. return false;
  17850. },
  17851. enumerable: true,
  17852. configurable: true
  17853. });
  17854. /**
  17855. * Returns the mesh itself by default, used by the class Mesh.
  17856. * Returned type : AbstractMesh
  17857. */
  17858. AbstractMesh.prototype.getLOD = function (camera) {
  17859. return this;
  17860. };
  17861. /**
  17862. * Returns 0 by default, used by the class Mesh.
  17863. * Returns an integer.
  17864. */
  17865. AbstractMesh.prototype.getTotalVertices = function () {
  17866. return 0;
  17867. };
  17868. /**
  17869. * Returns null by default, used by the class Mesh.
  17870. * Returned type : integer array
  17871. */
  17872. AbstractMesh.prototype.getIndices = function () {
  17873. return null;
  17874. };
  17875. /**
  17876. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17877. * Returned type : float array or Float32Array
  17878. */
  17879. AbstractMesh.prototype.getVerticesData = function (kind) {
  17880. return null;
  17881. };
  17882. /**
  17883. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17884. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17885. * The `data` are either a numeric array either a Float32Array.
  17886. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17887. * 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).
  17888. * Note that a new underlying VertexBuffer object is created each call.
  17889. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17890. *
  17891. * Possible `kind` values :
  17892. * - BABYLON.VertexBuffer.PositionKind
  17893. * - BABYLON.VertexBuffer.UVKind
  17894. * - BABYLON.VertexBuffer.UV2Kind
  17895. * - BABYLON.VertexBuffer.UV3Kind
  17896. * - BABYLON.VertexBuffer.UV4Kind
  17897. * - BABYLON.VertexBuffer.UV5Kind
  17898. * - BABYLON.VertexBuffer.UV6Kind
  17899. * - BABYLON.VertexBuffer.ColorKind
  17900. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17901. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17902. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17903. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17904. *
  17905. * Returns the Mesh.
  17906. */
  17907. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17908. return this;
  17909. };
  17910. /**
  17911. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17912. * If the mesh has no geometry, it is simply returned as it is.
  17913. * The `data` are either a numeric array either a Float32Array.
  17914. * No new underlying VertexBuffer object is created.
  17915. * 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.
  17916. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17917. *
  17918. * Possible `kind` values :
  17919. * - BABYLON.VertexBuffer.PositionKind
  17920. * - BABYLON.VertexBuffer.UVKind
  17921. * - BABYLON.VertexBuffer.UV2Kind
  17922. * - BABYLON.VertexBuffer.UV3Kind
  17923. * - BABYLON.VertexBuffer.UV4Kind
  17924. * - BABYLON.VertexBuffer.UV5Kind
  17925. * - BABYLON.VertexBuffer.UV6Kind
  17926. * - BABYLON.VertexBuffer.ColorKind
  17927. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17928. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17929. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17930. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17931. *
  17932. * Returns the Mesh.
  17933. */
  17934. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17935. return this;
  17936. };
  17937. /**
  17938. * Sets the mesh indices.
  17939. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17940. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17941. * This method creates a new index buffer each call.
  17942. * Returns the Mesh.
  17943. */
  17944. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17945. return this;
  17946. };
  17947. /** Returns false by default, used by the class Mesh.
  17948. * Returns a boolean
  17949. */
  17950. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17951. return false;
  17952. };
  17953. /**
  17954. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17955. * Returns a BoundingInfo
  17956. */
  17957. AbstractMesh.prototype.getBoundingInfo = function () {
  17958. if (this._masterMesh) {
  17959. return this._masterMesh.getBoundingInfo();
  17960. }
  17961. if (!this._boundingInfo) {
  17962. // this._boundingInfo is being created here
  17963. this._updateBoundingInfo();
  17964. }
  17965. // cannot be null.
  17966. return this._boundingInfo;
  17967. };
  17968. /**
  17969. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17970. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17971. */
  17972. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17973. if (includeDescendants === void 0) { includeDescendants = true; }
  17974. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17975. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17976. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17977. if (maxDimension === 0) {
  17978. return this;
  17979. }
  17980. var scale = 1 / maxDimension;
  17981. this.scaling.scaleInPlace(scale);
  17982. return this;
  17983. };
  17984. /**
  17985. * Sets a mesh new object BoundingInfo.
  17986. * Returns the AbstractMesh.
  17987. */
  17988. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17989. this._boundingInfo = boundingInfo;
  17990. return this;
  17991. };
  17992. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17993. get: function () {
  17994. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17995. },
  17996. enumerable: true,
  17997. configurable: true
  17998. });
  17999. AbstractMesh.prototype._preActivate = function () {
  18000. };
  18001. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18002. };
  18003. AbstractMesh.prototype._activate = function (renderId) {
  18004. this._renderId = renderId;
  18005. };
  18006. /**
  18007. * Returns the latest update of the World matrix
  18008. * Returns a Matrix.
  18009. */
  18010. AbstractMesh.prototype.getWorldMatrix = function () {
  18011. if (this._masterMesh) {
  18012. return this._masterMesh.getWorldMatrix();
  18013. }
  18014. return _super.prototype.getWorldMatrix.call(this);
  18015. };
  18016. /**
  18017. * Returns the latest update of the World matrix determinant.
  18018. */
  18019. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18020. if (this._masterMesh) {
  18021. return this._masterMesh._getWorldMatrixDeterminant();
  18022. }
  18023. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18024. };
  18025. // ================================== Point of View Movement =================================
  18026. /**
  18027. * Perform relative position change from the point of view of behind the front of the mesh.
  18028. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18029. * Supports definition of mesh facing forward or backward.
  18030. * @param {number} amountRight
  18031. * @param {number} amountUp
  18032. * @param {number} amountForward
  18033. *
  18034. * Returns the AbstractMesh.
  18035. */
  18036. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18037. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18038. return this;
  18039. };
  18040. /**
  18041. * Calculate relative position change from the point of view of behind the front of the mesh.
  18042. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18043. * Supports definition of mesh facing forward or backward.
  18044. * @param {number} amountRight
  18045. * @param {number} amountUp
  18046. * @param {number} amountForward
  18047. *
  18048. * Returns a new Vector3.
  18049. */
  18050. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18051. var rotMatrix = new BABYLON.Matrix();
  18052. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18053. rotQuaternion.toRotationMatrix(rotMatrix);
  18054. var translationDelta = BABYLON.Vector3.Zero();
  18055. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18056. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18057. return translationDelta;
  18058. };
  18059. // ================================== Point of View Rotation =================================
  18060. /**
  18061. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18062. * Supports definition of mesh facing forward or backward.
  18063. * @param {number} flipBack
  18064. * @param {number} twirlClockwise
  18065. * @param {number} tiltRight
  18066. *
  18067. * Returns the AbstractMesh.
  18068. */
  18069. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18070. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18071. return this;
  18072. };
  18073. /**
  18074. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18075. * Supports definition of mesh facing forward or backward.
  18076. * @param {number} flipBack
  18077. * @param {number} twirlClockwise
  18078. * @param {number} tiltRight
  18079. *
  18080. * Returns a new Vector3.
  18081. */
  18082. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18083. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18084. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18085. };
  18086. /**
  18087. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18088. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18089. */
  18090. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18091. if (includeDescendants === void 0) { includeDescendants = true; }
  18092. this.computeWorldMatrix(true);
  18093. var min;
  18094. var max;
  18095. var boundingInfo = this.getBoundingInfo();
  18096. if (!this.subMeshes) {
  18097. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18098. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18099. }
  18100. else {
  18101. min = boundingInfo.boundingBox.minimumWorld;
  18102. max = boundingInfo.boundingBox.maximumWorld;
  18103. }
  18104. if (includeDescendants) {
  18105. var descendants = this.getDescendants(false);
  18106. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18107. var descendant = descendants_1[_i];
  18108. var childMesh = descendant;
  18109. childMesh.computeWorldMatrix(true);
  18110. //make sure we have the needed params to get mix and max
  18111. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18112. continue;
  18113. }
  18114. var childBoundingInfo = childMesh.getBoundingInfo();
  18115. var boundingBox = childBoundingInfo.boundingBox;
  18116. var minBox = boundingBox.minimumWorld;
  18117. var maxBox = boundingBox.maximumWorld;
  18118. BABYLON.Tools.CheckExtends(minBox, min, max);
  18119. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18120. }
  18121. }
  18122. return {
  18123. min: min,
  18124. max: max
  18125. };
  18126. };
  18127. /**
  18128. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18129. * Returns the AbstractMesh.
  18130. */
  18131. AbstractMesh.prototype._updateBoundingInfo = function () {
  18132. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18133. this._boundingInfo.update(this.worldMatrixFromCache);
  18134. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18135. return this;
  18136. };
  18137. /**
  18138. * Update a mesh's children BoundingInfo objects only.
  18139. * Returns the AbstractMesh.
  18140. */
  18141. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18142. if (!this.subMeshes) {
  18143. return this;
  18144. }
  18145. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18146. var subMesh = this.subMeshes[subIndex];
  18147. if (!subMesh.IsGlobal) {
  18148. subMesh.updateBoundingInfo(matrix);
  18149. }
  18150. }
  18151. return this;
  18152. };
  18153. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18154. // Bounding info
  18155. this._updateBoundingInfo();
  18156. };
  18157. /**
  18158. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18159. * A mesh is in the frustum if its bounding box intersects the frustum.
  18160. * Boolean returned.
  18161. */
  18162. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18163. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18164. };
  18165. /**
  18166. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18167. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18168. * Boolean returned.
  18169. */
  18170. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18171. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18172. ;
  18173. };
  18174. /**
  18175. * True if the mesh intersects another mesh or a SolidParticle object.
  18176. * 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)
  18177. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18178. * Returns a boolean.
  18179. */
  18180. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18181. if (precise === void 0) { precise = false; }
  18182. if (!this._boundingInfo || !mesh._boundingInfo) {
  18183. return false;
  18184. }
  18185. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18186. return true;
  18187. }
  18188. if (includeDescendants) {
  18189. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18190. var child = _a[_i];
  18191. if (child.intersectsMesh(mesh, precise, true)) {
  18192. return true;
  18193. }
  18194. }
  18195. }
  18196. return false;
  18197. };
  18198. /**
  18199. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18200. * Returns a boolean.
  18201. */
  18202. AbstractMesh.prototype.intersectsPoint = function (point) {
  18203. if (!this._boundingInfo) {
  18204. return false;
  18205. }
  18206. return this._boundingInfo.intersectsPoint(point);
  18207. };
  18208. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18209. return this.physicsImpostor;
  18210. };
  18211. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18212. if (camera === void 0) { camera = null; }
  18213. if (!camera) {
  18214. camera = this.getScene().activeCamera;
  18215. }
  18216. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18217. };
  18218. /**
  18219. * Returns the distance from the mesh to the active camera.
  18220. * Returns a float.
  18221. */
  18222. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18223. if (camera === void 0) { camera = null; }
  18224. if (!camera) {
  18225. camera = this.getScene().activeCamera;
  18226. }
  18227. return this.absolutePosition.subtract(camera.position).length();
  18228. };
  18229. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18230. if (!this.physicsImpostor) {
  18231. return this;
  18232. }
  18233. this.physicsImpostor.applyImpulse(force, contactPoint);
  18234. return this;
  18235. };
  18236. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18237. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18238. return this;
  18239. }
  18240. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18241. mainPivot: pivot1,
  18242. connectedPivot: pivot2,
  18243. nativeParams: options
  18244. });
  18245. return this;
  18246. };
  18247. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18248. // Collisions
  18249. /**
  18250. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18251. * Default `false`.
  18252. */
  18253. get: function () {
  18254. return this._checkCollisions;
  18255. },
  18256. set: function (collisionEnabled) {
  18257. this._checkCollisions = collisionEnabled;
  18258. if (this.getScene().workerCollisions) {
  18259. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18260. }
  18261. },
  18262. enumerable: true,
  18263. configurable: true
  18264. });
  18265. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18266. /**
  18267. * Gets Collider object used to compute collisions (not physics)
  18268. */
  18269. get: function () {
  18270. return this._collider;
  18271. },
  18272. enumerable: true,
  18273. configurable: true
  18274. });
  18275. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18276. var globalPosition = this.getAbsolutePosition();
  18277. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18278. if (!this._collider) {
  18279. this._collider = new BABYLON.Collider();
  18280. }
  18281. this._collider._radius = this.ellipsoid;
  18282. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18283. return this;
  18284. };
  18285. // Submeshes octree
  18286. /**
  18287. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18288. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18289. * Returns an Octree of submeshes.
  18290. */
  18291. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18292. if (maxCapacity === void 0) { maxCapacity = 64; }
  18293. if (maxDepth === void 0) { maxDepth = 2; }
  18294. if (!this._submeshesOctree) {
  18295. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18296. }
  18297. this.computeWorldMatrix(true);
  18298. var boundingInfo = this.getBoundingInfo();
  18299. // Update octree
  18300. var bbox = boundingInfo.boundingBox;
  18301. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18302. return this._submeshesOctree;
  18303. };
  18304. // Collisions
  18305. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18306. this._generatePointsArray();
  18307. if (!this._positions) {
  18308. return this;
  18309. }
  18310. // Transformation
  18311. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18312. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18313. subMesh._lastColliderWorldVertices = [];
  18314. subMesh._trianglePlanes = [];
  18315. var start = subMesh.verticesStart;
  18316. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18317. for (var i = start; i < end; i++) {
  18318. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18319. }
  18320. }
  18321. // Collide
  18322. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18323. if (collider.collisionFound) {
  18324. collider.collidedMesh = this;
  18325. }
  18326. return this;
  18327. };
  18328. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18329. var subMeshes;
  18330. var len;
  18331. // Octrees
  18332. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18333. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18334. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18335. len = intersections.length;
  18336. subMeshes = intersections.data;
  18337. }
  18338. else {
  18339. subMeshes = this.subMeshes;
  18340. len = subMeshes.length;
  18341. }
  18342. for (var index = 0; index < len; index++) {
  18343. var subMesh = subMeshes[index];
  18344. // Bounding test
  18345. if (len > 1 && !subMesh._checkCollision(collider))
  18346. continue;
  18347. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18348. }
  18349. return this;
  18350. };
  18351. AbstractMesh.prototype._checkCollision = function (collider) {
  18352. // Bounding box test
  18353. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18354. return this;
  18355. // Transformation matrix
  18356. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18357. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18358. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18359. return this;
  18360. };
  18361. // Picking
  18362. AbstractMesh.prototype._generatePointsArray = function () {
  18363. return false;
  18364. };
  18365. /**
  18366. * Checks if the passed Ray intersects with the mesh.
  18367. * Returns an object PickingInfo.
  18368. */
  18369. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18370. var pickingInfo = new BABYLON.PickingInfo();
  18371. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18372. return pickingInfo;
  18373. }
  18374. if (!this._generatePointsArray()) {
  18375. return pickingInfo;
  18376. }
  18377. var intersectInfo = null;
  18378. // Octrees
  18379. var subMeshes;
  18380. var len;
  18381. if (this._submeshesOctree && this.useOctreeForPicking) {
  18382. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18383. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18384. len = intersections.length;
  18385. subMeshes = intersections.data;
  18386. }
  18387. else {
  18388. subMeshes = this.subMeshes;
  18389. len = subMeshes.length;
  18390. }
  18391. for (var index = 0; index < len; index++) {
  18392. var subMesh = subMeshes[index];
  18393. // Bounding test
  18394. if (len > 1 && !subMesh.canIntersects(ray))
  18395. continue;
  18396. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18397. if (currentIntersectInfo) {
  18398. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18399. intersectInfo = currentIntersectInfo;
  18400. intersectInfo.subMeshId = index;
  18401. if (fastCheck) {
  18402. break;
  18403. }
  18404. }
  18405. }
  18406. }
  18407. if (intersectInfo) {
  18408. // Get picked point
  18409. var world = this.getWorldMatrix();
  18410. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18411. var direction = ray.direction.clone();
  18412. direction = direction.scale(intersectInfo.distance);
  18413. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18414. var pickedPoint = worldOrigin.add(worldDirection);
  18415. // Return result
  18416. pickingInfo.hit = true;
  18417. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18418. pickingInfo.pickedPoint = pickedPoint;
  18419. pickingInfo.pickedMesh = this;
  18420. pickingInfo.bu = intersectInfo.bu || 0;
  18421. pickingInfo.bv = intersectInfo.bv || 0;
  18422. pickingInfo.faceId = intersectInfo.faceId;
  18423. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18424. return pickingInfo;
  18425. }
  18426. return pickingInfo;
  18427. };
  18428. /**
  18429. * Clones the mesh, used by the class Mesh.
  18430. * Just returns `null` for an AbstractMesh.
  18431. */
  18432. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18433. return null;
  18434. };
  18435. /**
  18436. * Disposes all the mesh submeshes.
  18437. * Returns the AbstractMesh.
  18438. */
  18439. AbstractMesh.prototype.releaseSubMeshes = function () {
  18440. if (this.subMeshes) {
  18441. while (this.subMeshes.length) {
  18442. this.subMeshes[0].dispose();
  18443. }
  18444. }
  18445. else {
  18446. this.subMeshes = new Array();
  18447. }
  18448. return this;
  18449. };
  18450. /**
  18451. * Releases resources associated with this abstract mesh.
  18452. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18453. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18454. */
  18455. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18456. var _this = this;
  18457. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18458. var index;
  18459. // Smart Array Retainers.
  18460. this.getScene().freeActiveMeshes();
  18461. this.getScene().freeRenderingGroups();
  18462. // Action manager
  18463. if (this.actionManager !== undefined && this.actionManager !== null) {
  18464. this.actionManager.dispose();
  18465. this.actionManager = null;
  18466. }
  18467. // Skeleton
  18468. this.skeleton = null;
  18469. // Physics
  18470. if (this.physicsImpostor) {
  18471. this.physicsImpostor.dispose();
  18472. }
  18473. // Intersections in progress
  18474. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18475. var other = this._intersectionsInProgress[index];
  18476. var pos = other._intersectionsInProgress.indexOf(this);
  18477. other._intersectionsInProgress.splice(pos, 1);
  18478. }
  18479. this._intersectionsInProgress = [];
  18480. // Lights
  18481. var lights = this.getScene().lights;
  18482. lights.forEach(function (light) {
  18483. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18484. if (meshIndex !== -1) {
  18485. light.includedOnlyMeshes.splice(meshIndex, 1);
  18486. }
  18487. meshIndex = light.excludedMeshes.indexOf(_this);
  18488. if (meshIndex !== -1) {
  18489. light.excludedMeshes.splice(meshIndex, 1);
  18490. }
  18491. // Shadow generators
  18492. var generator = light.getShadowGenerator();
  18493. if (generator) {
  18494. var shadowMap = generator.getShadowMap();
  18495. if (shadowMap && shadowMap.renderList) {
  18496. meshIndex = shadowMap.renderList.indexOf(_this);
  18497. if (meshIndex !== -1) {
  18498. shadowMap.renderList.splice(meshIndex, 1);
  18499. }
  18500. }
  18501. }
  18502. });
  18503. // Edges
  18504. if (this._edgesRenderer) {
  18505. this._edgesRenderer.dispose();
  18506. this._edgesRenderer = null;
  18507. }
  18508. // SubMeshes
  18509. if (this.getClassName() !== "InstancedMesh") {
  18510. this.releaseSubMeshes();
  18511. }
  18512. // Octree
  18513. var sceneOctree = this.getScene().selectionOctree;
  18514. if (sceneOctree !== undefined && sceneOctree !== null) {
  18515. var index = sceneOctree.dynamicContent.indexOf(this);
  18516. if (index !== -1) {
  18517. sceneOctree.dynamicContent.splice(index, 1);
  18518. }
  18519. }
  18520. // Query
  18521. var engine = this.getScene().getEngine();
  18522. if (this._occlusionQuery) {
  18523. this._isOcclusionQueryInProgress = false;
  18524. engine.deleteQuery(this._occlusionQuery);
  18525. this._occlusionQuery = null;
  18526. }
  18527. // Engine
  18528. engine.wipeCaches();
  18529. // Remove from scene
  18530. this.getScene().removeMesh(this);
  18531. if (disposeMaterialAndTextures) {
  18532. if (this.material) {
  18533. this.material.dispose(false, true);
  18534. }
  18535. }
  18536. if (!doNotRecurse) {
  18537. // Particles
  18538. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18539. if (this.getScene().particleSystems[index].emitter === this) {
  18540. this.getScene().particleSystems[index].dispose();
  18541. index--;
  18542. }
  18543. }
  18544. }
  18545. // facet data
  18546. if (this._facetDataEnabled) {
  18547. this.disableFacetData();
  18548. }
  18549. this.onAfterWorldMatrixUpdateObservable.clear();
  18550. this.onCollideObservable.clear();
  18551. this.onCollisionPositionChangeObservable.clear();
  18552. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18553. };
  18554. /**
  18555. * Adds the passed mesh as a child to the current mesh.
  18556. * Returns the AbstractMesh.
  18557. */
  18558. AbstractMesh.prototype.addChild = function (mesh) {
  18559. mesh.setParent(this);
  18560. return this;
  18561. };
  18562. /**
  18563. * Removes the passed mesh from the current mesh children list.
  18564. * Returns the AbstractMesh.
  18565. */
  18566. AbstractMesh.prototype.removeChild = function (mesh) {
  18567. mesh.setParent(null);
  18568. return this;
  18569. };
  18570. // Facet data
  18571. /**
  18572. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18573. * Returns the AbstractMesh.
  18574. */
  18575. AbstractMesh.prototype._initFacetData = function () {
  18576. if (!this._facetNormals) {
  18577. this._facetNormals = new Array();
  18578. }
  18579. if (!this._facetPositions) {
  18580. this._facetPositions = new Array();
  18581. }
  18582. if (!this._facetPartitioning) {
  18583. this._facetPartitioning = new Array();
  18584. }
  18585. this._facetNb = (this.getIndices().length / 3) | 0;
  18586. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18587. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18588. for (var f = 0; f < this._facetNb; f++) {
  18589. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18590. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18591. }
  18592. this._facetDataEnabled = true;
  18593. return this;
  18594. };
  18595. /**
  18596. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18597. * This method can be called within the render loop.
  18598. * 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.
  18599. * Returns the AbstractMesh.
  18600. */
  18601. AbstractMesh.prototype.updateFacetData = function () {
  18602. if (!this._facetDataEnabled) {
  18603. this._initFacetData();
  18604. }
  18605. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18606. var indices = this.getIndices();
  18607. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18608. var bInfo = this.getBoundingInfo();
  18609. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18610. // init arrays, matrix and sort function on first call
  18611. this._facetDepthSortEnabled = true;
  18612. if (indices instanceof Uint16Array) {
  18613. this._depthSortedIndices = new Uint16Array(indices);
  18614. }
  18615. else if (indices instanceof Uint32Array) {
  18616. this._depthSortedIndices = new Uint32Array(indices);
  18617. }
  18618. else {
  18619. var needs32bits = false;
  18620. for (var i = 0; i < indices.length; i++) {
  18621. if (indices[i] > 65535) {
  18622. needs32bits = true;
  18623. break;
  18624. }
  18625. }
  18626. if (needs32bits) {
  18627. this._depthSortedIndices = new Uint32Array(indices);
  18628. }
  18629. else {
  18630. this._depthSortedIndices = new Uint16Array(indices);
  18631. }
  18632. }
  18633. this._facetDepthSortFunction = function (f1, f2) {
  18634. return (f2.sqDistance - f1.sqDistance);
  18635. };
  18636. if (!this._facetDepthSortFrom) {
  18637. var camera = this.getScene().activeCamera;
  18638. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18639. }
  18640. this._depthSortedFacets = [];
  18641. for (var f = 0; f < this._facetNb; f++) {
  18642. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18643. this._depthSortedFacets.push(depthSortedFacet);
  18644. }
  18645. this._invertedMatrix = BABYLON.Matrix.Identity();
  18646. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18647. }
  18648. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18649. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18650. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18651. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18652. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18653. this._subDiv.max = this._partitioningSubdivisions;
  18654. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18655. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18656. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18657. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18658. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18659. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18660. // set the parameters for ComputeNormals()
  18661. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18662. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18663. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18664. this._facetParameters.bInfo = bInfo;
  18665. this._facetParameters.bbSize = this._bbSize;
  18666. this._facetParameters.subDiv = this._subDiv;
  18667. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18668. this._facetParameters.depthSort = this._facetDepthSort;
  18669. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18670. this.computeWorldMatrix(true);
  18671. this._worldMatrix.invertToRef(this._invertedMatrix);
  18672. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18673. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18674. }
  18675. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18676. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18677. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18678. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18679. var l = (this._depthSortedIndices.length / 3) | 0;
  18680. for (var f = 0; f < l; f++) {
  18681. var sind = this._depthSortedFacets[f].ind;
  18682. this._depthSortedIndices[f * 3] = indices[sind];
  18683. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18684. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18685. }
  18686. this.updateIndices(this._depthSortedIndices);
  18687. }
  18688. return this;
  18689. };
  18690. /**
  18691. * Returns the facetLocalNormals array.
  18692. * The normals are expressed in the mesh local space.
  18693. */
  18694. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18695. if (!this._facetNormals) {
  18696. this.updateFacetData();
  18697. }
  18698. return this._facetNormals;
  18699. };
  18700. /**
  18701. * Returns the facetLocalPositions array.
  18702. * The facet positions are expressed in the mesh local space.
  18703. */
  18704. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18705. if (!this._facetPositions) {
  18706. this.updateFacetData();
  18707. }
  18708. return this._facetPositions;
  18709. };
  18710. /**
  18711. * Returns the facetLocalPartioning array.
  18712. */
  18713. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18714. if (!this._facetPartitioning) {
  18715. this.updateFacetData();
  18716. }
  18717. return this._facetPartitioning;
  18718. };
  18719. /**
  18720. * Returns the i-th facet position in the world system.
  18721. * This method allocates a new Vector3 per call.
  18722. */
  18723. AbstractMesh.prototype.getFacetPosition = function (i) {
  18724. var pos = BABYLON.Vector3.Zero();
  18725. this.getFacetPositionToRef(i, pos);
  18726. return pos;
  18727. };
  18728. /**
  18729. * Sets the reference Vector3 with the i-th facet position in the world system.
  18730. * Returns the AbstractMesh.
  18731. */
  18732. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18733. var localPos = (this.getFacetLocalPositions())[i];
  18734. var world = this.getWorldMatrix();
  18735. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18736. return this;
  18737. };
  18738. /**
  18739. * Returns the i-th facet normal in the world system.
  18740. * This method allocates a new Vector3 per call.
  18741. */
  18742. AbstractMesh.prototype.getFacetNormal = function (i) {
  18743. var norm = BABYLON.Vector3.Zero();
  18744. this.getFacetNormalToRef(i, norm);
  18745. return norm;
  18746. };
  18747. /**
  18748. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18749. * Returns the AbstractMesh.
  18750. */
  18751. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18752. var localNorm = (this.getFacetLocalNormals())[i];
  18753. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18754. return this;
  18755. };
  18756. /**
  18757. * 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).
  18758. */
  18759. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18760. var bInfo = this.getBoundingInfo();
  18761. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18762. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18763. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18764. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18765. return null;
  18766. }
  18767. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18768. };
  18769. /**
  18770. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18771. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18772. * 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.
  18773. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18774. * 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.
  18775. */
  18776. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18777. if (checkFace === void 0) { checkFace = false; }
  18778. if (facing === void 0) { facing = true; }
  18779. var world = this.getWorldMatrix();
  18780. var invMat = BABYLON.Tmp.Matrix[5];
  18781. world.invertToRef(invMat);
  18782. var invVect = BABYLON.Tmp.Vector3[8];
  18783. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18784. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18785. if (projected) {
  18786. // tranform the local computed projected vector to world coordinates
  18787. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18788. }
  18789. return closest;
  18790. };
  18791. /**
  18792. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18793. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18794. * 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.
  18795. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18796. * 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.
  18797. */
  18798. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18799. if (checkFace === void 0) { checkFace = false; }
  18800. if (facing === void 0) { facing = true; }
  18801. var closest = null;
  18802. var tmpx = 0.0;
  18803. var tmpy = 0.0;
  18804. var tmpz = 0.0;
  18805. var d = 0.0; // tmp dot facet normal * facet position
  18806. var t0 = 0.0;
  18807. var projx = 0.0;
  18808. var projy = 0.0;
  18809. var projz = 0.0;
  18810. // Get all the facets in the same partitioning block than (x, y, z)
  18811. var facetPositions = this.getFacetLocalPositions();
  18812. var facetNormals = this.getFacetLocalNormals();
  18813. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18814. if (!facetsInBlock) {
  18815. return null;
  18816. }
  18817. // Get the closest facet to (x, y, z)
  18818. var shortest = Number.MAX_VALUE; // init distance vars
  18819. var tmpDistance = shortest;
  18820. var fib; // current facet in the block
  18821. var norm; // current facet normal
  18822. var p0; // current facet barycenter position
  18823. // loop on all the facets in the current partitioning block
  18824. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18825. fib = facetsInBlock[idx];
  18826. norm = facetNormals[fib];
  18827. p0 = facetPositions[fib];
  18828. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18829. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18830. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18831. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18832. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18833. projx = x + norm.x * t0;
  18834. projy = y + norm.y * t0;
  18835. projz = z + norm.z * t0;
  18836. tmpx = projx - x;
  18837. tmpy = projy - y;
  18838. tmpz = projz - z;
  18839. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18840. if (tmpDistance < shortest) {
  18841. shortest = tmpDistance;
  18842. closest = fib;
  18843. if (projected) {
  18844. projected.x = projx;
  18845. projected.y = projy;
  18846. projected.z = projz;
  18847. }
  18848. }
  18849. }
  18850. }
  18851. return closest;
  18852. };
  18853. /**
  18854. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18855. */
  18856. AbstractMesh.prototype.getFacetDataParameters = function () {
  18857. return this._facetParameters;
  18858. };
  18859. /**
  18860. * Disables the feature FacetData and frees the related memory.
  18861. * Returns the AbstractMesh.
  18862. */
  18863. AbstractMesh.prototype.disableFacetData = function () {
  18864. if (this._facetDataEnabled) {
  18865. this._facetDataEnabled = false;
  18866. this._facetPositions = new Array();
  18867. this._facetNormals = new Array();
  18868. this._facetPartitioning = new Array();
  18869. this._facetParameters = null;
  18870. this._depthSortedIndices = new Uint32Array(0);
  18871. }
  18872. return this;
  18873. };
  18874. /**
  18875. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18876. * Returns the mesh.
  18877. */
  18878. AbstractMesh.prototype.updateIndices = function (indices) {
  18879. return this;
  18880. };
  18881. /**
  18882. * The mesh Geometry. Actually used by the Mesh object.
  18883. * Returns a blank geometry object.
  18884. */
  18885. /**
  18886. * Creates new normals data for the mesh.
  18887. * @param updatable.
  18888. */
  18889. AbstractMesh.prototype.createNormals = function (updatable) {
  18890. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18891. var indices = this.getIndices();
  18892. var normals;
  18893. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18894. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18895. }
  18896. else {
  18897. normals = [];
  18898. }
  18899. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18900. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18901. };
  18902. /**
  18903. * Align the mesh with a normal.
  18904. * Returns the mesh.
  18905. */
  18906. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18907. if (!upDirection) {
  18908. upDirection = BABYLON.Axis.Y;
  18909. }
  18910. var axisX = BABYLON.Tmp.Vector3[0];
  18911. var axisZ = BABYLON.Tmp.Vector3[1];
  18912. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18913. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18914. if (this.rotationQuaternion) {
  18915. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18916. }
  18917. else {
  18918. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18919. }
  18920. return this;
  18921. };
  18922. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18923. var engine = this.getEngine();
  18924. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18925. this._isOccluded = false;
  18926. return;
  18927. }
  18928. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18929. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18930. if (isOcclusionQueryAvailable) {
  18931. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18932. this._isOcclusionQueryInProgress = false;
  18933. this._occlusionInternalRetryCounter = 0;
  18934. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18935. }
  18936. else {
  18937. this._occlusionInternalRetryCounter++;
  18938. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18939. this._isOcclusionQueryInProgress = false;
  18940. this._occlusionInternalRetryCounter = 0;
  18941. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18942. // if strict continue the last state of the object.
  18943. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18944. }
  18945. else {
  18946. return;
  18947. }
  18948. }
  18949. }
  18950. var scene = this.getScene();
  18951. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18952. if (!this._occlusionQuery) {
  18953. this._occlusionQuery = engine.createQuery();
  18954. }
  18955. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18956. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18957. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18958. this._isOcclusionQueryInProgress = true;
  18959. };
  18960. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18961. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18962. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18963. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18964. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18965. return AbstractMesh;
  18966. }(BABYLON.TransformNode));
  18967. BABYLON.AbstractMesh = AbstractMesh;
  18968. })(BABYLON || (BABYLON = {}));
  18969. //# sourceMappingURL=babylon.abstractMesh.js.map
  18970. var BABYLON;
  18971. (function (BABYLON) {
  18972. /**
  18973. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18974. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18975. * 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.
  18976. */
  18977. var Light = /** @class */ (function (_super) {
  18978. __extends(Light, _super);
  18979. /**
  18980. * Creates a Light object in the scene.
  18981. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18982. * @param name The firendly name of the light
  18983. * @param scene The scene the light belongs too
  18984. */
  18985. function Light(name, scene) {
  18986. var _this = _super.call(this, name, scene) || this;
  18987. /**
  18988. * Diffuse gives the basic color to an object.
  18989. */
  18990. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18991. /**
  18992. * Specular produces a highlight color on an object.
  18993. * Note: This is note affecting PBR materials.
  18994. */
  18995. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18996. /**
  18997. * Strength of the light.
  18998. * Note: By default it is define in the framework own unit.
  18999. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19000. */
  19001. _this.intensity = 1.0;
  19002. /**
  19003. * Defines how far from the source the light is impacting in scene units.
  19004. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19005. */
  19006. _this.range = Number.MAX_VALUE;
  19007. /**
  19008. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19009. * of light.
  19010. */
  19011. _this._photometricScale = 1.0;
  19012. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19013. _this._radius = 0.00001;
  19014. /**
  19015. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19016. * exceeding the number allowed of the materials.
  19017. */
  19018. _this.renderPriority = 0;
  19019. /**
  19020. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19021. * the current shadow generator.
  19022. */
  19023. _this.shadowEnabled = true;
  19024. _this._excludeWithLayerMask = 0;
  19025. _this._includeOnlyWithLayerMask = 0;
  19026. _this._lightmapMode = 0;
  19027. /**
  19028. * @ignore Internal use only.
  19029. */
  19030. _this._excludedMeshesIds = new Array();
  19031. /**
  19032. * @ignore Internal use only.
  19033. */
  19034. _this._includedOnlyMeshesIds = new Array();
  19035. _this.getScene().addLight(_this);
  19036. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19037. _this._buildUniformLayout();
  19038. _this.includedOnlyMeshes = new Array();
  19039. _this.excludedMeshes = new Array();
  19040. _this._resyncMeshes();
  19041. return _this;
  19042. }
  19043. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19044. /**
  19045. * If every light affecting the material is in this lightmapMode,
  19046. * material.lightmapTexture adds or multiplies
  19047. * (depends on material.useLightmapAsShadowmap)
  19048. * after every other light calculations.
  19049. */
  19050. get: function () {
  19051. return Light._LIGHTMAP_DEFAULT;
  19052. },
  19053. enumerable: true,
  19054. configurable: true
  19055. });
  19056. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19057. /**
  19058. * material.lightmapTexture as only diffuse lighting from this light
  19059. * adds only specular lighting from this light
  19060. * adds dynamic shadows
  19061. */
  19062. get: function () {
  19063. return Light._LIGHTMAP_SPECULAR;
  19064. },
  19065. enumerable: true,
  19066. configurable: true
  19067. });
  19068. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19069. /**
  19070. * material.lightmapTexture as only lighting
  19071. * no light calculation from this light
  19072. * only adds dynamic shadows from this light
  19073. */
  19074. get: function () {
  19075. return Light._LIGHTMAP_SHADOWSONLY;
  19076. },
  19077. enumerable: true,
  19078. configurable: true
  19079. });
  19080. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19081. /**
  19082. * Each light type uses the default quantity according to its type:
  19083. * point/spot lights use luminous intensity
  19084. * directional lights use illuminance
  19085. */
  19086. get: function () {
  19087. return Light._INTENSITYMODE_AUTOMATIC;
  19088. },
  19089. enumerable: true,
  19090. configurable: true
  19091. });
  19092. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19093. /**
  19094. * lumen (lm)
  19095. */
  19096. get: function () {
  19097. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19098. },
  19099. enumerable: true,
  19100. configurable: true
  19101. });
  19102. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19103. /**
  19104. * candela (lm/sr)
  19105. */
  19106. get: function () {
  19107. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19108. },
  19109. enumerable: true,
  19110. configurable: true
  19111. });
  19112. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19113. /**
  19114. * lux (lm/m^2)
  19115. */
  19116. get: function () {
  19117. return Light._INTENSITYMODE_ILLUMINANCE;
  19118. },
  19119. enumerable: true,
  19120. configurable: true
  19121. });
  19122. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19123. /**
  19124. * nit (cd/m^2)
  19125. */
  19126. get: function () {
  19127. return Light._INTENSITYMODE_LUMINANCE;
  19128. },
  19129. enumerable: true,
  19130. configurable: true
  19131. });
  19132. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19133. /**
  19134. * Light type const id of the point light.
  19135. */
  19136. get: function () {
  19137. return Light._LIGHTTYPEID_POINTLIGHT;
  19138. },
  19139. enumerable: true,
  19140. configurable: true
  19141. });
  19142. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19143. /**
  19144. * Light type const id of the directional light.
  19145. */
  19146. get: function () {
  19147. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19148. },
  19149. enumerable: true,
  19150. configurable: true
  19151. });
  19152. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19153. /**
  19154. * Light type const id of the spot light.
  19155. */
  19156. get: function () {
  19157. return Light._LIGHTTYPEID_SPOTLIGHT;
  19158. },
  19159. enumerable: true,
  19160. configurable: true
  19161. });
  19162. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19163. /**
  19164. * Light type const id of the hemispheric light.
  19165. */
  19166. get: function () {
  19167. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19168. },
  19169. enumerable: true,
  19170. configurable: true
  19171. });
  19172. Object.defineProperty(Light.prototype, "intensityMode", {
  19173. /**
  19174. * Gets the photometric scale used to interpret the intensity.
  19175. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19176. */
  19177. get: function () {
  19178. return this._intensityMode;
  19179. },
  19180. /**
  19181. * Sets the photometric scale used to interpret the intensity.
  19182. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19183. */
  19184. set: function (value) {
  19185. this._intensityMode = value;
  19186. this._computePhotometricScale();
  19187. },
  19188. enumerable: true,
  19189. configurable: true
  19190. });
  19191. ;
  19192. ;
  19193. Object.defineProperty(Light.prototype, "radius", {
  19194. /**
  19195. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19196. */
  19197. get: function () {
  19198. return this._radius;
  19199. },
  19200. /**
  19201. * sets the light radius used by PBR Materials to simulate soft area lights.
  19202. */
  19203. set: function (value) {
  19204. this._radius = value;
  19205. this._computePhotometricScale();
  19206. },
  19207. enumerable: true,
  19208. configurable: true
  19209. });
  19210. ;
  19211. ;
  19212. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19213. /**
  19214. * Gets the only meshes impacted by this light.
  19215. */
  19216. get: function () {
  19217. return this._includedOnlyMeshes;
  19218. },
  19219. /**
  19220. * Sets the only meshes impacted by this light.
  19221. */
  19222. set: function (value) {
  19223. this._includedOnlyMeshes = value;
  19224. this._hookArrayForIncludedOnly(value);
  19225. },
  19226. enumerable: true,
  19227. configurable: true
  19228. });
  19229. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19230. /**
  19231. * Gets the meshes not impacted by this light.
  19232. */
  19233. get: function () {
  19234. return this._excludedMeshes;
  19235. },
  19236. /**
  19237. * Sets the meshes not impacted by this light.
  19238. */
  19239. set: function (value) {
  19240. this._excludedMeshes = value;
  19241. this._hookArrayForExcluded(value);
  19242. },
  19243. enumerable: true,
  19244. configurable: true
  19245. });
  19246. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19247. /**
  19248. * Gets the layer id use to find what meshes are not impacted by the light.
  19249. * Inactive if 0
  19250. */
  19251. get: function () {
  19252. return this._excludeWithLayerMask;
  19253. },
  19254. /**
  19255. * Sets the layer id use to find what meshes are not impacted by the light.
  19256. * Inactive if 0
  19257. */
  19258. set: function (value) {
  19259. this._excludeWithLayerMask = value;
  19260. this._resyncMeshes();
  19261. },
  19262. enumerable: true,
  19263. configurable: true
  19264. });
  19265. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19266. /**
  19267. * Gets the layer id use to find what meshes are impacted by the light.
  19268. * Inactive if 0
  19269. */
  19270. get: function () {
  19271. return this._includeOnlyWithLayerMask;
  19272. },
  19273. /**
  19274. * Sets the layer id use to find what meshes are impacted by the light.
  19275. * Inactive if 0
  19276. */
  19277. set: function (value) {
  19278. this._includeOnlyWithLayerMask = value;
  19279. this._resyncMeshes();
  19280. },
  19281. enumerable: true,
  19282. configurable: true
  19283. });
  19284. Object.defineProperty(Light.prototype, "lightmapMode", {
  19285. /**
  19286. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19287. */
  19288. get: function () {
  19289. return this._lightmapMode;
  19290. },
  19291. /**
  19292. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19293. */
  19294. set: function (value) {
  19295. if (this._lightmapMode === value) {
  19296. return;
  19297. }
  19298. this._lightmapMode = value;
  19299. this._markMeshesAsLightDirty();
  19300. },
  19301. enumerable: true,
  19302. configurable: true
  19303. });
  19304. /**
  19305. * Returns the string "Light".
  19306. * @returns the class name
  19307. */
  19308. Light.prototype.getClassName = function () {
  19309. return "Light";
  19310. };
  19311. /**
  19312. * Converts the light information to a readable string for debug purpose.
  19313. * @param fullDetails Supports for multiple levels of logging within scene loading
  19314. * @returns the human readable light info
  19315. */
  19316. Light.prototype.toString = function (fullDetails) {
  19317. var ret = "Name: " + this.name;
  19318. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19319. if (this.animations) {
  19320. for (var i = 0; i < this.animations.length; i++) {
  19321. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19322. }
  19323. }
  19324. if (fullDetails) {
  19325. }
  19326. return ret;
  19327. };
  19328. /**
  19329. * Set the enabled state of this node.
  19330. * @param value - the new enabled state
  19331. * @see isEnabled
  19332. */
  19333. Light.prototype.setEnabled = function (value) {
  19334. _super.prototype.setEnabled.call(this, value);
  19335. this._resyncMeshes();
  19336. };
  19337. /**
  19338. * Returns the Light associated shadow generator if any.
  19339. * @return the associated shadow generator.
  19340. */
  19341. Light.prototype.getShadowGenerator = function () {
  19342. return this._shadowGenerator;
  19343. };
  19344. /**
  19345. * Returns a Vector3, the absolute light position in the World.
  19346. * @returns the world space position of the light
  19347. */
  19348. Light.prototype.getAbsolutePosition = function () {
  19349. return BABYLON.Vector3.Zero();
  19350. };
  19351. /**
  19352. * Specifies if the light will affect the passed mesh.
  19353. * @param mesh The mesh to test against the light
  19354. * @return true the mesh is affected otherwise, false.
  19355. */
  19356. Light.prototype.canAffectMesh = function (mesh) {
  19357. if (!mesh) {
  19358. return true;
  19359. }
  19360. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19361. return false;
  19362. }
  19363. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19364. return false;
  19365. }
  19366. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19367. return false;
  19368. }
  19369. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19370. return false;
  19371. }
  19372. return true;
  19373. };
  19374. /**
  19375. * Computes and Returns the light World matrix.
  19376. * @returns the world matrix
  19377. */
  19378. Light.prototype.getWorldMatrix = function () {
  19379. this._currentRenderId = this.getScene().getRenderId();
  19380. var worldMatrix = this._getWorldMatrix();
  19381. if (this.parent && this.parent.getWorldMatrix) {
  19382. if (!this._parentedWorldMatrix) {
  19383. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19384. }
  19385. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19386. this._markSyncedWithParent();
  19387. return this._parentedWorldMatrix;
  19388. }
  19389. return worldMatrix;
  19390. };
  19391. /**
  19392. * Sort function to order lights for rendering.
  19393. * @param a First Light object to compare to second.
  19394. * @param b Second Light object to compare first.
  19395. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19396. */
  19397. Light.CompareLightsPriority = function (a, b) {
  19398. //shadow-casting lights have priority over non-shadow-casting lights
  19399. //the renderPrioirty is a secondary sort criterion
  19400. if (a.shadowEnabled !== b.shadowEnabled) {
  19401. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19402. }
  19403. return b.renderPriority - a.renderPriority;
  19404. };
  19405. /**
  19406. * Releases resources associated with this node.
  19407. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19408. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19409. */
  19410. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19411. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19412. if (this._shadowGenerator) {
  19413. this._shadowGenerator.dispose();
  19414. this._shadowGenerator = null;
  19415. }
  19416. // Animations
  19417. this.getScene().stopAnimation(this);
  19418. // Remove from meshes
  19419. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19420. var mesh = _a[_i];
  19421. mesh._removeLightSource(this);
  19422. }
  19423. this._uniformBuffer.dispose();
  19424. // Remove from scene
  19425. this.getScene().removeLight(this);
  19426. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19427. };
  19428. /**
  19429. * Returns the light type ID (integer).
  19430. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19431. */
  19432. Light.prototype.getTypeID = function () {
  19433. return 0;
  19434. };
  19435. /**
  19436. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19437. * @returns the scaled intensity in intensity mode unit
  19438. */
  19439. Light.prototype.getScaledIntensity = function () {
  19440. return this._photometricScale * this.intensity;
  19441. };
  19442. /**
  19443. * Returns a new Light object, named "name", from the current one.
  19444. * @param name The name of the cloned light
  19445. * @returns the new created light
  19446. */
  19447. Light.prototype.clone = function (name) {
  19448. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19449. if (!constructor) {
  19450. return null;
  19451. }
  19452. return BABYLON.SerializationHelper.Clone(constructor, this);
  19453. };
  19454. /**
  19455. * Serializes the current light into a Serialization object.
  19456. * @returns the serialized object.
  19457. */
  19458. Light.prototype.serialize = function () {
  19459. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19460. // Type
  19461. serializationObject.type = this.getTypeID();
  19462. // Parent
  19463. if (this.parent) {
  19464. serializationObject.parentId = this.parent.id;
  19465. }
  19466. // Inclusion / exclusions
  19467. if (this.excludedMeshes.length > 0) {
  19468. serializationObject.excludedMeshesIds = [];
  19469. this.excludedMeshes.forEach(function (mesh) {
  19470. serializationObject.excludedMeshesIds.push(mesh.id);
  19471. });
  19472. }
  19473. if (this.includedOnlyMeshes.length > 0) {
  19474. serializationObject.includedOnlyMeshesIds = [];
  19475. this.includedOnlyMeshes.forEach(function (mesh) {
  19476. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19477. });
  19478. }
  19479. // Animations
  19480. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19481. serializationObject.ranges = this.serializeAnimationRanges();
  19482. return serializationObject;
  19483. };
  19484. /**
  19485. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19486. * This new light is named "name" and added to the passed scene.
  19487. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19488. * @param name The friendly name of the light
  19489. * @param scene The scene the new light will belong to
  19490. * @returns the constructor function
  19491. */
  19492. Light.GetConstructorFromName = function (type, name, scene) {
  19493. switch (type) {
  19494. case 0:
  19495. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19496. case 1:
  19497. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19498. case 2:
  19499. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19500. case 3:
  19501. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19502. }
  19503. return null;
  19504. };
  19505. /**
  19506. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19507. * @param parsedLight The JSON representation of the light
  19508. * @param scene The scene to create the parsed light in
  19509. * @returns the created light after parsing
  19510. */
  19511. Light.Parse = function (parsedLight, scene) {
  19512. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19513. if (!constructor) {
  19514. return null;
  19515. }
  19516. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19517. // Inclusion / exclusions
  19518. if (parsedLight.excludedMeshesIds) {
  19519. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19520. }
  19521. if (parsedLight.includedOnlyMeshesIds) {
  19522. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19523. }
  19524. // Parent
  19525. if (parsedLight.parentId) {
  19526. light._waitingParentId = parsedLight.parentId;
  19527. }
  19528. // Animations
  19529. if (parsedLight.animations) {
  19530. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19531. var parsedAnimation = parsedLight.animations[animationIndex];
  19532. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19533. }
  19534. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19535. }
  19536. if (parsedLight.autoAnimate) {
  19537. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19538. }
  19539. return light;
  19540. };
  19541. Light.prototype._hookArrayForExcluded = function (array) {
  19542. var _this = this;
  19543. var oldPush = array.push;
  19544. array.push = function () {
  19545. var items = [];
  19546. for (var _i = 0; _i < arguments.length; _i++) {
  19547. items[_i] = arguments[_i];
  19548. }
  19549. var result = oldPush.apply(array, items);
  19550. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19551. var item = items_1[_a];
  19552. item._resyncLighSource(_this);
  19553. }
  19554. return result;
  19555. };
  19556. var oldSplice = array.splice;
  19557. array.splice = function (index, deleteCount) {
  19558. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19559. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19560. var item = deleted_1[_i];
  19561. item._resyncLighSource(_this);
  19562. }
  19563. return deleted;
  19564. };
  19565. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19566. var item = array_1[_i];
  19567. item._resyncLighSource(this);
  19568. }
  19569. };
  19570. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19571. var _this = this;
  19572. var oldPush = array.push;
  19573. array.push = function () {
  19574. var items = [];
  19575. for (var _i = 0; _i < arguments.length; _i++) {
  19576. items[_i] = arguments[_i];
  19577. }
  19578. var result = oldPush.apply(array, items);
  19579. _this._resyncMeshes();
  19580. return result;
  19581. };
  19582. var oldSplice = array.splice;
  19583. array.splice = function (index, deleteCount) {
  19584. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19585. _this._resyncMeshes();
  19586. return deleted;
  19587. };
  19588. this._resyncMeshes();
  19589. };
  19590. Light.prototype._resyncMeshes = function () {
  19591. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19592. var mesh = _a[_i];
  19593. mesh._resyncLighSource(this);
  19594. }
  19595. };
  19596. /**
  19597. * Forces the meshes to update their light related information in their rendering used effects
  19598. * @ignore Internal Use Only
  19599. */
  19600. Light.prototype._markMeshesAsLightDirty = function () {
  19601. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19602. var mesh = _a[_i];
  19603. if (mesh._lightSources.indexOf(this) !== -1) {
  19604. mesh._markSubMeshesAsLightDirty();
  19605. }
  19606. }
  19607. };
  19608. /**
  19609. * Recomputes the cached photometric scale if needed.
  19610. */
  19611. Light.prototype._computePhotometricScale = function () {
  19612. this._photometricScale = this._getPhotometricScale();
  19613. this.getScene().resetCachedMaterial();
  19614. };
  19615. /**
  19616. * Returns the Photometric Scale according to the light type and intensity mode.
  19617. */
  19618. Light.prototype._getPhotometricScale = function () {
  19619. var photometricScale = 0.0;
  19620. var lightTypeID = this.getTypeID();
  19621. //get photometric mode
  19622. var photometricMode = this.intensityMode;
  19623. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19624. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19625. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19626. }
  19627. else {
  19628. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19629. }
  19630. }
  19631. //compute photometric scale
  19632. switch (lightTypeID) {
  19633. case Light.LIGHTTYPEID_POINTLIGHT:
  19634. case Light.LIGHTTYPEID_SPOTLIGHT:
  19635. switch (photometricMode) {
  19636. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19637. photometricScale = 1.0 / (4.0 * Math.PI);
  19638. break;
  19639. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19640. photometricScale = 1.0;
  19641. break;
  19642. case Light.INTENSITYMODE_LUMINANCE:
  19643. photometricScale = this.radius * this.radius;
  19644. break;
  19645. }
  19646. break;
  19647. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19648. switch (photometricMode) {
  19649. case Light.INTENSITYMODE_ILLUMINANCE:
  19650. photometricScale = 1.0;
  19651. break;
  19652. case Light.INTENSITYMODE_LUMINANCE:
  19653. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19654. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19655. var apexAngleRadians = this.radius;
  19656. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19657. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19658. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19659. photometricScale = solidAngle;
  19660. break;
  19661. }
  19662. break;
  19663. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19664. // No fall off in hemisperic light.
  19665. photometricScale = 1.0;
  19666. break;
  19667. }
  19668. return photometricScale;
  19669. };
  19670. /**
  19671. * Reorder the light in the scene according to their defined priority.
  19672. * @ignore Internal Use Only
  19673. */
  19674. Light.prototype._reorderLightsInScene = function () {
  19675. var scene = this.getScene();
  19676. if (this._renderPriority != 0) {
  19677. scene.requireLightSorting = true;
  19678. }
  19679. this.getScene().sortLightsByPriority();
  19680. };
  19681. //lightmapMode Consts
  19682. Light._LIGHTMAP_DEFAULT = 0;
  19683. Light._LIGHTMAP_SPECULAR = 1;
  19684. Light._LIGHTMAP_SHADOWSONLY = 2;
  19685. // Intensity Mode Consts
  19686. Light._INTENSITYMODE_AUTOMATIC = 0;
  19687. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19688. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19689. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19690. Light._INTENSITYMODE_LUMINANCE = 4;
  19691. // Light types ids const.
  19692. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19693. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19694. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19695. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19696. __decorate([
  19697. BABYLON.serializeAsColor3()
  19698. ], Light.prototype, "diffuse", void 0);
  19699. __decorate([
  19700. BABYLON.serializeAsColor3()
  19701. ], Light.prototype, "specular", void 0);
  19702. __decorate([
  19703. BABYLON.serialize()
  19704. ], Light.prototype, "intensity", void 0);
  19705. __decorate([
  19706. BABYLON.serialize()
  19707. ], Light.prototype, "range", void 0);
  19708. __decorate([
  19709. BABYLON.serialize()
  19710. ], Light.prototype, "intensityMode", null);
  19711. __decorate([
  19712. BABYLON.serialize()
  19713. ], Light.prototype, "radius", null);
  19714. __decorate([
  19715. BABYLON.serialize()
  19716. ], Light.prototype, "_renderPriority", void 0);
  19717. __decorate([
  19718. BABYLON.expandToProperty("_reorderLightsInScene")
  19719. ], Light.prototype, "renderPriority", void 0);
  19720. __decorate([
  19721. BABYLON.serialize()
  19722. ], Light.prototype, "shadowEnabled", void 0);
  19723. __decorate([
  19724. BABYLON.serialize("excludeWithLayerMask")
  19725. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19726. __decorate([
  19727. BABYLON.serialize("includeOnlyWithLayerMask")
  19728. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19729. __decorate([
  19730. BABYLON.serialize("lightmapMode")
  19731. ], Light.prototype, "_lightmapMode", void 0);
  19732. return Light;
  19733. }(BABYLON.Node));
  19734. BABYLON.Light = Light;
  19735. })(BABYLON || (BABYLON = {}));
  19736. //# sourceMappingURL=babylon.light.js.map
  19737. var BABYLON;
  19738. (function (BABYLON) {
  19739. var Camera = /** @class */ (function (_super) {
  19740. __extends(Camera, _super);
  19741. function Camera(name, position, scene) {
  19742. var _this = _super.call(this, name, scene) || this;
  19743. /**
  19744. * The vector the camera should consider as up.
  19745. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19746. */
  19747. _this.upVector = BABYLON.Vector3.Up();
  19748. _this.orthoLeft = null;
  19749. _this.orthoRight = null;
  19750. _this.orthoBottom = null;
  19751. _this.orthoTop = null;
  19752. /**
  19753. * FOV is set in Radians. (default is 0.8)
  19754. */
  19755. _this.fov = 0.8;
  19756. _this.minZ = 1;
  19757. _this.maxZ = 10000.0;
  19758. _this.inertia = 0.9;
  19759. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19760. _this.isIntermediate = false;
  19761. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19762. /**
  19763. * Restricts the camera to viewing objects with the same layerMask.
  19764. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19765. */
  19766. _this.layerMask = 0x0FFFFFFF;
  19767. /**
  19768. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19769. */
  19770. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19771. // Camera rig members
  19772. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19773. _this._rigCameras = new Array();
  19774. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19775. _this._skipRendering = false;
  19776. _this.customRenderTargets = new Array();
  19777. // Observables
  19778. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19779. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19780. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19781. _this.onRestoreStateObservable = new BABYLON.Observable();
  19782. // Cache
  19783. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19784. _this._projectionMatrix = new BABYLON.Matrix();
  19785. _this._doNotComputeProjectionMatrix = false;
  19786. _this._postProcesses = new Array();
  19787. _this._transformMatrix = BABYLON.Matrix.Zero();
  19788. _this._activeMeshes = new BABYLON.SmartArray(256);
  19789. _this._globalPosition = BABYLON.Vector3.Zero();
  19790. _this._refreshFrustumPlanes = true;
  19791. _this.getScene().addCamera(_this);
  19792. if (!_this.getScene().activeCamera) {
  19793. _this.getScene().activeCamera = _this;
  19794. }
  19795. _this.position = position;
  19796. return _this;
  19797. }
  19798. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19799. get: function () {
  19800. return Camera._PERSPECTIVE_CAMERA;
  19801. },
  19802. enumerable: true,
  19803. configurable: true
  19804. });
  19805. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19806. get: function () {
  19807. return Camera._ORTHOGRAPHIC_CAMERA;
  19808. },
  19809. enumerable: true,
  19810. configurable: true
  19811. });
  19812. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19813. /**
  19814. * This is the default FOV mode for perspective cameras.
  19815. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19816. *
  19817. */
  19818. get: function () {
  19819. return Camera._FOVMODE_VERTICAL_FIXED;
  19820. },
  19821. enumerable: true,
  19822. configurable: true
  19823. });
  19824. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19825. /**
  19826. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19827. *
  19828. */
  19829. get: function () {
  19830. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19831. },
  19832. enumerable: true,
  19833. configurable: true
  19834. });
  19835. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19836. get: function () {
  19837. return Camera._RIG_MODE_NONE;
  19838. },
  19839. enumerable: true,
  19840. configurable: true
  19841. });
  19842. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19843. get: function () {
  19844. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19845. },
  19846. enumerable: true,
  19847. configurable: true
  19848. });
  19849. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19850. get: function () {
  19851. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19852. },
  19853. enumerable: true,
  19854. configurable: true
  19855. });
  19856. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19857. get: function () {
  19858. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19859. },
  19860. enumerable: true,
  19861. configurable: true
  19862. });
  19863. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19864. get: function () {
  19865. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19866. },
  19867. enumerable: true,
  19868. configurable: true
  19869. });
  19870. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19871. get: function () {
  19872. return Camera._RIG_MODE_VR;
  19873. },
  19874. enumerable: true,
  19875. configurable: true
  19876. });
  19877. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19878. get: function () {
  19879. return Camera._RIG_MODE_WEBVR;
  19880. },
  19881. enumerable: true,
  19882. configurable: true
  19883. });
  19884. /**
  19885. * Store current camera state (fov, position, etc..)
  19886. */
  19887. Camera.prototype.storeState = function () {
  19888. this._stateStored = true;
  19889. this._storedFov = this.fov;
  19890. return this;
  19891. };
  19892. /**
  19893. * Restores the camera state values if it has been stored. You must call storeState() first
  19894. */
  19895. Camera.prototype._restoreStateValues = function () {
  19896. if (!this._stateStored) {
  19897. return false;
  19898. }
  19899. this.fov = this._storedFov;
  19900. return true;
  19901. };
  19902. /**
  19903. * Restored camera state. You must call storeState() first
  19904. */
  19905. Camera.prototype.restoreState = function () {
  19906. if (this._restoreStateValues()) {
  19907. this.onRestoreStateObservable.notifyObservers(this);
  19908. return true;
  19909. }
  19910. return false;
  19911. };
  19912. Camera.prototype.getClassName = function () {
  19913. return "Camera";
  19914. };
  19915. /**
  19916. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19917. */
  19918. Camera.prototype.toString = function (fullDetails) {
  19919. var ret = "Name: " + this.name;
  19920. ret += ", type: " + this.getClassName();
  19921. if (this.animations) {
  19922. for (var i = 0; i < this.animations.length; i++) {
  19923. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19924. }
  19925. }
  19926. if (fullDetails) {
  19927. }
  19928. return ret;
  19929. };
  19930. Object.defineProperty(Camera.prototype, "globalPosition", {
  19931. get: function () {
  19932. return this._globalPosition;
  19933. },
  19934. enumerable: true,
  19935. configurable: true
  19936. });
  19937. Camera.prototype.getActiveMeshes = function () {
  19938. return this._activeMeshes;
  19939. };
  19940. Camera.prototype.isActiveMesh = function (mesh) {
  19941. return (this._activeMeshes.indexOf(mesh) !== -1);
  19942. };
  19943. //Cache
  19944. Camera.prototype._initCache = function () {
  19945. _super.prototype._initCache.call(this);
  19946. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19947. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19948. this._cache.mode = undefined;
  19949. this._cache.minZ = undefined;
  19950. this._cache.maxZ = undefined;
  19951. this._cache.fov = undefined;
  19952. this._cache.fovMode = undefined;
  19953. this._cache.aspectRatio = undefined;
  19954. this._cache.orthoLeft = undefined;
  19955. this._cache.orthoRight = undefined;
  19956. this._cache.orthoBottom = undefined;
  19957. this._cache.orthoTop = undefined;
  19958. this._cache.renderWidth = undefined;
  19959. this._cache.renderHeight = undefined;
  19960. };
  19961. Camera.prototype._updateCache = function (ignoreParentClass) {
  19962. if (!ignoreParentClass) {
  19963. _super.prototype._updateCache.call(this);
  19964. }
  19965. this._cache.position.copyFrom(this.position);
  19966. this._cache.upVector.copyFrom(this.upVector);
  19967. };
  19968. // Synchronized
  19969. Camera.prototype._isSynchronized = function () {
  19970. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19971. };
  19972. Camera.prototype._isSynchronizedViewMatrix = function () {
  19973. if (!_super.prototype._isSynchronized.call(this))
  19974. return false;
  19975. return this._cache.position.equals(this.position)
  19976. && this._cache.upVector.equals(this.upVector)
  19977. && this.isSynchronizedWithParent();
  19978. };
  19979. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19980. var check = this._cache.mode === this.mode
  19981. && this._cache.minZ === this.minZ
  19982. && this._cache.maxZ === this.maxZ;
  19983. if (!check) {
  19984. return false;
  19985. }
  19986. var engine = this.getEngine();
  19987. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19988. check = this._cache.fov === this.fov
  19989. && this._cache.fovMode === this.fovMode
  19990. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19991. }
  19992. else {
  19993. check = this._cache.orthoLeft === this.orthoLeft
  19994. && this._cache.orthoRight === this.orthoRight
  19995. && this._cache.orthoBottom === this.orthoBottom
  19996. && this._cache.orthoTop === this.orthoTop
  19997. && this._cache.renderWidth === engine.getRenderWidth()
  19998. && this._cache.renderHeight === engine.getRenderHeight();
  19999. }
  20000. return check;
  20001. };
  20002. // Controls
  20003. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20004. };
  20005. Camera.prototype.detachControl = function (element) {
  20006. };
  20007. Camera.prototype.update = function () {
  20008. this._checkInputs();
  20009. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20010. this._updateRigCameras();
  20011. }
  20012. };
  20013. Camera.prototype._checkInputs = function () {
  20014. this.onAfterCheckInputsObservable.notifyObservers(this);
  20015. };
  20016. Object.defineProperty(Camera.prototype, "rigCameras", {
  20017. get: function () {
  20018. return this._rigCameras;
  20019. },
  20020. enumerable: true,
  20021. configurable: true
  20022. });
  20023. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20024. get: function () {
  20025. return this._rigPostProcess;
  20026. },
  20027. enumerable: true,
  20028. configurable: true
  20029. });
  20030. /**
  20031. * Internal, gets the first post proces.
  20032. * @returns the first post process to be run on this camera.
  20033. */
  20034. Camera.prototype._getFirstPostProcess = function () {
  20035. for (var pp in this._postProcesses) {
  20036. if (this._postProcesses[pp] !== null) {
  20037. return this._postProcesses[pp];
  20038. }
  20039. }
  20040. return null;
  20041. };
  20042. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20043. // invalidate framebuffer
  20044. var firstPostProcess = this._getFirstPostProcess();
  20045. if (firstPostProcess) {
  20046. firstPostProcess.markTextureDirty();
  20047. }
  20048. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20049. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20050. var cam = this._rigCameras[i];
  20051. var rigPostProcess = cam._rigPostProcess;
  20052. // for VR rig, there does not have to be a post process
  20053. if (rigPostProcess) {
  20054. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20055. if (isPass) {
  20056. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20057. cam.isIntermediate = this._postProcesses.length === 0;
  20058. }
  20059. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20060. rigPostProcess.markTextureDirty();
  20061. }
  20062. else {
  20063. cam._postProcesses = this._postProcesses.slice(0);
  20064. }
  20065. }
  20066. };
  20067. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20068. if (insertAt === void 0) { insertAt = null; }
  20069. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20070. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20071. return 0;
  20072. }
  20073. if (insertAt == null || insertAt < 0) {
  20074. this._postProcesses.push(postProcess);
  20075. }
  20076. else if (this._postProcesses[insertAt] === null) {
  20077. this._postProcesses[insertAt] = postProcess;
  20078. }
  20079. else {
  20080. this._postProcesses.splice(insertAt, 0, postProcess);
  20081. }
  20082. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20083. return this._postProcesses.indexOf(postProcess);
  20084. };
  20085. Camera.prototype.detachPostProcess = function (postProcess) {
  20086. var idx = this._postProcesses.indexOf(postProcess);
  20087. if (idx !== -1) {
  20088. this._postProcesses[idx] = null;
  20089. }
  20090. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20091. };
  20092. Camera.prototype.getWorldMatrix = function () {
  20093. if (!this._worldMatrix) {
  20094. this._worldMatrix = BABYLON.Matrix.Identity();
  20095. }
  20096. var viewMatrix = this.getViewMatrix();
  20097. viewMatrix.invertToRef(this._worldMatrix);
  20098. return this._worldMatrix;
  20099. };
  20100. Camera.prototype._getViewMatrix = function () {
  20101. return BABYLON.Matrix.Identity();
  20102. };
  20103. Camera.prototype.getViewMatrix = function (force) {
  20104. if (!force && this._isSynchronizedViewMatrix()) {
  20105. return this._computedViewMatrix;
  20106. }
  20107. this.updateCache();
  20108. this._computedViewMatrix = this._getViewMatrix();
  20109. this._currentRenderId = this.getScene().getRenderId();
  20110. this._refreshFrustumPlanes = true;
  20111. if (!this.parent || !this.parent.getWorldMatrix) {
  20112. this._globalPosition.copyFrom(this.position);
  20113. }
  20114. else {
  20115. if (!this._worldMatrix) {
  20116. this._worldMatrix = BABYLON.Matrix.Identity();
  20117. }
  20118. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20119. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20120. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20121. this._computedViewMatrix.invert();
  20122. this._markSyncedWithParent();
  20123. }
  20124. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20125. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20126. }
  20127. this.onViewMatrixChangedObservable.notifyObservers(this);
  20128. return this._computedViewMatrix;
  20129. };
  20130. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20131. this._doNotComputeProjectionMatrix = true;
  20132. if (projection !== undefined) {
  20133. this._projectionMatrix = projection;
  20134. }
  20135. };
  20136. ;
  20137. Camera.prototype.unfreezeProjectionMatrix = function () {
  20138. this._doNotComputeProjectionMatrix = false;
  20139. };
  20140. ;
  20141. Camera.prototype.getProjectionMatrix = function (force) {
  20142. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20143. return this._projectionMatrix;
  20144. }
  20145. // Cache
  20146. this._cache.mode = this.mode;
  20147. this._cache.minZ = this.minZ;
  20148. this._cache.maxZ = this.maxZ;
  20149. // Matrix
  20150. this._refreshFrustumPlanes = true;
  20151. var engine = this.getEngine();
  20152. var scene = this.getScene();
  20153. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20154. this._cache.fov = this.fov;
  20155. this._cache.fovMode = this.fovMode;
  20156. this._cache.aspectRatio = engine.getAspectRatio(this);
  20157. if (this.minZ <= 0) {
  20158. this.minZ = 0.1;
  20159. }
  20160. if (scene.useRightHandedSystem) {
  20161. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20162. }
  20163. else {
  20164. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20165. }
  20166. }
  20167. else {
  20168. var halfWidth = engine.getRenderWidth() / 2.0;
  20169. var halfHeight = engine.getRenderHeight() / 2.0;
  20170. if (scene.useRightHandedSystem) {
  20171. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20172. }
  20173. else {
  20174. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20175. }
  20176. this._cache.orthoLeft = this.orthoLeft;
  20177. this._cache.orthoRight = this.orthoRight;
  20178. this._cache.orthoBottom = this.orthoBottom;
  20179. this._cache.orthoTop = this.orthoTop;
  20180. this._cache.renderWidth = engine.getRenderWidth();
  20181. this._cache.renderHeight = engine.getRenderHeight();
  20182. }
  20183. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20184. return this._projectionMatrix;
  20185. };
  20186. Camera.prototype.getTranformationMatrix = function () {
  20187. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20188. return this._transformMatrix;
  20189. };
  20190. Camera.prototype.updateFrustumPlanes = function () {
  20191. if (!this._refreshFrustumPlanes) {
  20192. return;
  20193. }
  20194. this.getTranformationMatrix();
  20195. if (!this._frustumPlanes) {
  20196. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20197. }
  20198. else {
  20199. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20200. }
  20201. this._refreshFrustumPlanes = false;
  20202. };
  20203. Camera.prototype.isInFrustum = function (target) {
  20204. this.updateFrustumPlanes();
  20205. return target.isInFrustum(this._frustumPlanes);
  20206. };
  20207. Camera.prototype.isCompletelyInFrustum = function (target) {
  20208. this.updateFrustumPlanes();
  20209. return target.isCompletelyInFrustum(this._frustumPlanes);
  20210. };
  20211. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20212. if (length === void 0) { length = 100; }
  20213. if (!transform) {
  20214. transform = this.getWorldMatrix();
  20215. }
  20216. if (!origin) {
  20217. origin = this.position;
  20218. }
  20219. var forward = new BABYLON.Vector3(0, 0, 1);
  20220. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20221. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20222. return new BABYLON.Ray(origin, direction, length);
  20223. };
  20224. /**
  20225. * Releases resources associated with this node.
  20226. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20227. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20228. */
  20229. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20230. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20231. // Observables
  20232. this.onViewMatrixChangedObservable.clear();
  20233. this.onProjectionMatrixChangedObservable.clear();
  20234. this.onAfterCheckInputsObservable.clear();
  20235. this.onRestoreStateObservable.clear();
  20236. // Inputs
  20237. if (this.inputs) {
  20238. this.inputs.clear();
  20239. }
  20240. // Animations
  20241. this.getScene().stopAnimation(this);
  20242. // Remove from scene
  20243. this.getScene().removeCamera(this);
  20244. while (this._rigCameras.length > 0) {
  20245. var camera = this._rigCameras.pop();
  20246. if (camera) {
  20247. camera.dispose();
  20248. }
  20249. }
  20250. // Postprocesses
  20251. if (this._rigPostProcess) {
  20252. this._rigPostProcess.dispose(this);
  20253. this._rigPostProcess = null;
  20254. this._postProcesses = [];
  20255. }
  20256. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20257. this._rigPostProcess = null;
  20258. this._postProcesses = [];
  20259. }
  20260. else {
  20261. var i = this._postProcesses.length;
  20262. while (--i >= 0) {
  20263. var postProcess = this._postProcesses[i];
  20264. if (postProcess) {
  20265. postProcess.dispose(this);
  20266. }
  20267. }
  20268. }
  20269. // Render targets
  20270. var i = this.customRenderTargets.length;
  20271. while (--i >= 0) {
  20272. this.customRenderTargets[i].dispose();
  20273. }
  20274. this.customRenderTargets = [];
  20275. // Active Meshes
  20276. this._activeMeshes.dispose();
  20277. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20278. };
  20279. Object.defineProperty(Camera.prototype, "leftCamera", {
  20280. // ---- Camera rigs section ----
  20281. get: function () {
  20282. if (this._rigCameras.length < 1) {
  20283. return null;
  20284. }
  20285. return this._rigCameras[0];
  20286. },
  20287. enumerable: true,
  20288. configurable: true
  20289. });
  20290. Object.defineProperty(Camera.prototype, "rightCamera", {
  20291. get: function () {
  20292. if (this._rigCameras.length < 2) {
  20293. return null;
  20294. }
  20295. return this._rigCameras[1];
  20296. },
  20297. enumerable: true,
  20298. configurable: true
  20299. });
  20300. Camera.prototype.getLeftTarget = function () {
  20301. if (this._rigCameras.length < 1) {
  20302. return null;
  20303. }
  20304. return this._rigCameras[0].getTarget();
  20305. };
  20306. Camera.prototype.getRightTarget = function () {
  20307. if (this._rigCameras.length < 2) {
  20308. return null;
  20309. }
  20310. return this._rigCameras[1].getTarget();
  20311. };
  20312. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20313. if (this.cameraRigMode === mode) {
  20314. return;
  20315. }
  20316. while (this._rigCameras.length > 0) {
  20317. var camera = this._rigCameras.pop();
  20318. if (camera) {
  20319. camera.dispose();
  20320. }
  20321. }
  20322. this.cameraRigMode = mode;
  20323. this._cameraRigParams = {};
  20324. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20325. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20326. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20327. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20328. // create the rig cameras, unless none
  20329. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20330. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20331. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20332. if (leftCamera && rightCamera) {
  20333. this._rigCameras.push(leftCamera);
  20334. this._rigCameras.push(rightCamera);
  20335. }
  20336. }
  20337. switch (this.cameraRigMode) {
  20338. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20339. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20340. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20341. break;
  20342. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20343. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20344. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20345. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20346. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20347. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20348. break;
  20349. case Camera.RIG_MODE_VR:
  20350. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20351. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20352. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20353. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20354. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20355. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20356. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20357. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20358. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20359. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20360. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20361. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20362. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20363. if (metrics.compensateDistortion) {
  20364. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20365. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20366. }
  20367. break;
  20368. case Camera.RIG_MODE_WEBVR:
  20369. if (rigParams.vrDisplay) {
  20370. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20371. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20372. //Left eye
  20373. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20374. this._rigCameras[0].setCameraRigParameter("left", true);
  20375. //leaving this for future reference
  20376. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20377. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20378. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20379. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20380. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20381. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20382. this._rigCameras[0].parent = this;
  20383. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20384. //Right eye
  20385. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20386. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20387. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20388. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20389. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20390. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20391. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20392. this._rigCameras[1].parent = this;
  20393. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20394. if (Camera.UseAlternateWebVRRendering) {
  20395. this._rigCameras[1]._skipRendering = true;
  20396. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20397. }
  20398. }
  20399. break;
  20400. }
  20401. this._cascadePostProcessesToRigCams();
  20402. this.update();
  20403. };
  20404. Camera.prototype._getVRProjectionMatrix = function () {
  20405. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20406. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20407. return this._projectionMatrix;
  20408. };
  20409. Camera.prototype._updateCameraRotationMatrix = function () {
  20410. //Here for WebVR
  20411. };
  20412. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20413. //Here for WebVR
  20414. };
  20415. /**
  20416. * This function MUST be overwritten by the different WebVR cameras available.
  20417. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20418. */
  20419. Camera.prototype._getWebVRProjectionMatrix = function () {
  20420. return BABYLON.Matrix.Identity();
  20421. };
  20422. /**
  20423. * This function MUST be overwritten by the different WebVR cameras available.
  20424. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20425. */
  20426. Camera.prototype._getWebVRViewMatrix = function () {
  20427. return BABYLON.Matrix.Identity();
  20428. };
  20429. Camera.prototype.setCameraRigParameter = function (name, value) {
  20430. if (!this._cameraRigParams) {
  20431. this._cameraRigParams = {};
  20432. }
  20433. this._cameraRigParams[name] = value;
  20434. //provisionnally:
  20435. if (name === "interaxialDistance") {
  20436. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20437. }
  20438. };
  20439. /**
  20440. * needs to be overridden by children so sub has required properties to be copied
  20441. */
  20442. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20443. return null;
  20444. };
  20445. /**
  20446. * May need to be overridden by children
  20447. */
  20448. Camera.prototype._updateRigCameras = function () {
  20449. for (var i = 0; i < this._rigCameras.length; i++) {
  20450. this._rigCameras[i].minZ = this.minZ;
  20451. this._rigCameras[i].maxZ = this.maxZ;
  20452. this._rigCameras[i].fov = this.fov;
  20453. }
  20454. // only update viewport when ANAGLYPH
  20455. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20456. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20457. }
  20458. };
  20459. Camera.prototype._setupInputs = function () {
  20460. };
  20461. Camera.prototype.serialize = function () {
  20462. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20463. // Type
  20464. serializationObject.type = this.getClassName();
  20465. // Parent
  20466. if (this.parent) {
  20467. serializationObject.parentId = this.parent.id;
  20468. }
  20469. if (this.inputs) {
  20470. this.inputs.serialize(serializationObject);
  20471. }
  20472. // Animations
  20473. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20474. serializationObject.ranges = this.serializeAnimationRanges();
  20475. return serializationObject;
  20476. };
  20477. Camera.prototype.clone = function (name) {
  20478. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20479. };
  20480. Camera.prototype.getDirection = function (localAxis) {
  20481. var result = BABYLON.Vector3.Zero();
  20482. this.getDirectionToRef(localAxis, result);
  20483. return result;
  20484. };
  20485. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20486. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20487. };
  20488. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20489. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20490. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20491. switch (type) {
  20492. case "ArcRotateCamera":
  20493. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20494. case "DeviceOrientationCamera":
  20495. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20496. case "FollowCamera":
  20497. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20498. case "ArcFollowCamera":
  20499. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20500. case "GamepadCamera":
  20501. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20502. case "TouchCamera":
  20503. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20504. case "VirtualJoysticksCamera":
  20505. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20506. case "WebVRFreeCamera":
  20507. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20508. case "WebVRGamepadCamera":
  20509. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20510. case "VRDeviceOrientationFreeCamera":
  20511. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20512. case "VRDeviceOrientationGamepadCamera":
  20513. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20514. case "AnaglyphArcRotateCamera":
  20515. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20516. case "AnaglyphFreeCamera":
  20517. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20518. case "AnaglyphGamepadCamera":
  20519. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20520. case "AnaglyphUniversalCamera":
  20521. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20522. case "StereoscopicArcRotateCamera":
  20523. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20524. case "StereoscopicFreeCamera":
  20525. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20526. case "StereoscopicGamepadCamera":
  20527. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20528. case "StereoscopicUniversalCamera":
  20529. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20530. case "FreeCamera":// Forcing Universal here
  20531. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20532. default:// Universal Camera is the default value
  20533. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20534. }
  20535. };
  20536. Camera.prototype.computeWorldMatrix = function () {
  20537. return this.getWorldMatrix();
  20538. };
  20539. Camera.Parse = function (parsedCamera, scene) {
  20540. var type = parsedCamera.type;
  20541. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20542. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20543. // Parent
  20544. if (parsedCamera.parentId) {
  20545. camera._waitingParentId = parsedCamera.parentId;
  20546. }
  20547. //If camera has an input manager, let it parse inputs settings
  20548. if (camera.inputs) {
  20549. camera.inputs.parse(parsedCamera);
  20550. camera._setupInputs();
  20551. }
  20552. if (camera.setPosition) {
  20553. camera.position.copyFromFloats(0, 0, 0);
  20554. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20555. }
  20556. // Target
  20557. if (parsedCamera.target) {
  20558. if (camera.setTarget) {
  20559. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20560. }
  20561. }
  20562. // Apply 3d rig, when found
  20563. if (parsedCamera.cameraRigMode) {
  20564. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20565. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20566. }
  20567. // Animations
  20568. if (parsedCamera.animations) {
  20569. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20570. var parsedAnimation = parsedCamera.animations[animationIndex];
  20571. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20572. }
  20573. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20574. }
  20575. if (parsedCamera.autoAnimate) {
  20576. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20577. }
  20578. return camera;
  20579. };
  20580. // Statics
  20581. Camera._PERSPECTIVE_CAMERA = 0;
  20582. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20583. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20584. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20585. Camera._RIG_MODE_NONE = 0;
  20586. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20587. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20588. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20589. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20590. Camera._RIG_MODE_VR = 20;
  20591. Camera._RIG_MODE_WEBVR = 21;
  20592. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20593. Camera.UseAlternateWebVRRendering = false;
  20594. __decorate([
  20595. BABYLON.serializeAsVector3()
  20596. ], Camera.prototype, "position", void 0);
  20597. __decorate([
  20598. BABYLON.serializeAsVector3()
  20599. ], Camera.prototype, "upVector", void 0);
  20600. __decorate([
  20601. BABYLON.serialize()
  20602. ], Camera.prototype, "orthoLeft", void 0);
  20603. __decorate([
  20604. BABYLON.serialize()
  20605. ], Camera.prototype, "orthoRight", void 0);
  20606. __decorate([
  20607. BABYLON.serialize()
  20608. ], Camera.prototype, "orthoBottom", void 0);
  20609. __decorate([
  20610. BABYLON.serialize()
  20611. ], Camera.prototype, "orthoTop", void 0);
  20612. __decorate([
  20613. BABYLON.serialize()
  20614. ], Camera.prototype, "fov", void 0);
  20615. __decorate([
  20616. BABYLON.serialize()
  20617. ], Camera.prototype, "minZ", void 0);
  20618. __decorate([
  20619. BABYLON.serialize()
  20620. ], Camera.prototype, "maxZ", void 0);
  20621. __decorate([
  20622. BABYLON.serialize()
  20623. ], Camera.prototype, "inertia", void 0);
  20624. __decorate([
  20625. BABYLON.serialize()
  20626. ], Camera.prototype, "mode", void 0);
  20627. __decorate([
  20628. BABYLON.serialize()
  20629. ], Camera.prototype, "layerMask", void 0);
  20630. __decorate([
  20631. BABYLON.serialize()
  20632. ], Camera.prototype, "fovMode", void 0);
  20633. __decorate([
  20634. BABYLON.serialize()
  20635. ], Camera.prototype, "cameraRigMode", void 0);
  20636. __decorate([
  20637. BABYLON.serialize()
  20638. ], Camera.prototype, "interaxialDistance", void 0);
  20639. __decorate([
  20640. BABYLON.serialize()
  20641. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20642. return Camera;
  20643. }(BABYLON.Node));
  20644. BABYLON.Camera = Camera;
  20645. })(BABYLON || (BABYLON = {}));
  20646. //# sourceMappingURL=babylon.camera.js.map
  20647. var BABYLON;
  20648. (function (BABYLON) {
  20649. var RenderingManager = /** @class */ (function () {
  20650. function RenderingManager(scene) {
  20651. this._renderingGroups = new Array();
  20652. this._autoClearDepthStencil = {};
  20653. this._customOpaqueSortCompareFn = {};
  20654. this._customAlphaTestSortCompareFn = {};
  20655. this._customTransparentSortCompareFn = {};
  20656. this._renderinGroupInfo = null;
  20657. this._scene = scene;
  20658. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20659. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20660. }
  20661. }
  20662. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20663. if (depth === void 0) { depth = true; }
  20664. if (stencil === void 0) { stencil = true; }
  20665. if (this._depthStencilBufferAlreadyCleaned) {
  20666. return;
  20667. }
  20668. this._scene.getEngine().clear(null, false, depth, stencil);
  20669. this._depthStencilBufferAlreadyCleaned = true;
  20670. };
  20671. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20672. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20673. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20674. var info = null;
  20675. if (observable) {
  20676. if (!this._renderinGroupInfo) {
  20677. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20678. }
  20679. info = this._renderinGroupInfo;
  20680. info.scene = this._scene;
  20681. info.camera = this._scene.activeCamera;
  20682. }
  20683. // Dispatch sprites
  20684. if (renderSprites) {
  20685. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20686. var manager = this._scene.spriteManagers[index];
  20687. this.dispatchSprites(manager);
  20688. }
  20689. }
  20690. // Render
  20691. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20692. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20693. var renderingGroup = this._renderingGroups[index];
  20694. if (!renderingGroup && !observable)
  20695. continue;
  20696. var renderingGroupMask = 0;
  20697. // Fire PRECLEAR stage
  20698. if (observable && info) {
  20699. renderingGroupMask = Math.pow(2, index);
  20700. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20701. info.renderingGroupId = index;
  20702. observable.notifyObservers(info, renderingGroupMask);
  20703. }
  20704. // Clear depth/stencil if needed
  20705. if (RenderingManager.AUTOCLEAR) {
  20706. var autoClear = this._autoClearDepthStencil[index];
  20707. if (autoClear && autoClear.autoClear) {
  20708. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20709. }
  20710. }
  20711. if (observable && info) {
  20712. // Fire PREOPAQUE stage
  20713. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20714. observable.notifyObservers(info, renderingGroupMask);
  20715. // Fire PRETRANSPARENT stage
  20716. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20717. observable.notifyObservers(info, renderingGroupMask);
  20718. }
  20719. if (renderingGroup)
  20720. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20721. // Fire POSTTRANSPARENT stage
  20722. if (observable && info) {
  20723. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20724. observable.notifyObservers(info, renderingGroupMask);
  20725. }
  20726. }
  20727. };
  20728. RenderingManager.prototype.reset = function () {
  20729. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20730. var renderingGroup = this._renderingGroups[index];
  20731. if (renderingGroup) {
  20732. renderingGroup.prepare();
  20733. }
  20734. }
  20735. };
  20736. RenderingManager.prototype.dispose = function () {
  20737. this.freeRenderingGroups();
  20738. this._renderingGroups.length = 0;
  20739. };
  20740. /**
  20741. * Clear the info related to rendering groups preventing retention points during dispose.
  20742. */
  20743. RenderingManager.prototype.freeRenderingGroups = function () {
  20744. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20745. var renderingGroup = this._renderingGroups[index];
  20746. if (renderingGroup) {
  20747. renderingGroup.dispose();
  20748. }
  20749. }
  20750. };
  20751. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20752. if (this._renderingGroups[renderingGroupId] === undefined) {
  20753. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20754. }
  20755. };
  20756. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20757. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20758. this._prepareRenderingGroup(renderingGroupId);
  20759. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20760. };
  20761. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20762. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20763. this._prepareRenderingGroup(renderingGroupId);
  20764. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20765. };
  20766. /**
  20767. * @param subMesh The submesh to dispatch
  20768. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20769. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20770. */
  20771. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20772. if (mesh === undefined) {
  20773. mesh = subMesh.getMesh();
  20774. }
  20775. var renderingGroupId = mesh.renderingGroupId || 0;
  20776. this._prepareRenderingGroup(renderingGroupId);
  20777. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20778. };
  20779. /**
  20780. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20781. * This allowed control for front to back rendering or reversly depending of the special needs.
  20782. *
  20783. * @param renderingGroupId The rendering group id corresponding to its index
  20784. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20785. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20786. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20787. */
  20788. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20789. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20790. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20791. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20792. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20793. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20794. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20795. if (this._renderingGroups[renderingGroupId]) {
  20796. var group = this._renderingGroups[renderingGroupId];
  20797. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20798. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20799. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20800. }
  20801. };
  20802. /**
  20803. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20804. *
  20805. * @param renderingGroupId The rendering group id corresponding to its index
  20806. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20807. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20808. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20809. */
  20810. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20811. if (depth === void 0) { depth = true; }
  20812. if (stencil === void 0) { stencil = true; }
  20813. this._autoClearDepthStencil[renderingGroupId] = {
  20814. autoClear: autoClearDepthStencil,
  20815. depth: depth,
  20816. stencil: stencil
  20817. };
  20818. };
  20819. /**
  20820. * The max id used for rendering groups (not included)
  20821. */
  20822. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20823. /**
  20824. * The min id used for rendering groups (included)
  20825. */
  20826. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20827. /**
  20828. * Used to globally prevent autoclearing scenes.
  20829. */
  20830. RenderingManager.AUTOCLEAR = true;
  20831. return RenderingManager;
  20832. }());
  20833. BABYLON.RenderingManager = RenderingManager;
  20834. })(BABYLON || (BABYLON = {}));
  20835. //# sourceMappingURL=babylon.renderingManager.js.map
  20836. var BABYLON;
  20837. (function (BABYLON) {
  20838. var RenderingGroup = /** @class */ (function () {
  20839. /**
  20840. * Creates a new rendering group.
  20841. * @param index The rendering group index
  20842. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20843. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20844. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20845. */
  20846. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20847. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20848. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20849. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20850. this.index = index;
  20851. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20852. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20853. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20854. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20855. this._particleSystems = new BABYLON.SmartArray(256);
  20856. this._spriteManagers = new BABYLON.SmartArray(256);
  20857. this._edgesRenderers = new BABYLON.SmartArray(16);
  20858. this._scene = scene;
  20859. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20860. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20861. this.transparentSortCompareFn = transparentSortCompareFn;
  20862. }
  20863. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20864. /**
  20865. * Set the opaque sort comparison function.
  20866. * If null the sub meshes will be render in the order they were created
  20867. */
  20868. set: function (value) {
  20869. this._opaqueSortCompareFn = value;
  20870. if (value) {
  20871. this._renderOpaque = this.renderOpaqueSorted;
  20872. }
  20873. else {
  20874. this._renderOpaque = RenderingGroup.renderUnsorted;
  20875. }
  20876. },
  20877. enumerable: true,
  20878. configurable: true
  20879. });
  20880. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20881. /**
  20882. * Set the alpha test sort comparison function.
  20883. * If null the sub meshes will be render in the order they were created
  20884. */
  20885. set: function (value) {
  20886. this._alphaTestSortCompareFn = value;
  20887. if (value) {
  20888. this._renderAlphaTest = this.renderAlphaTestSorted;
  20889. }
  20890. else {
  20891. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20892. }
  20893. },
  20894. enumerable: true,
  20895. configurable: true
  20896. });
  20897. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20898. /**
  20899. * Set the transparent sort comparison function.
  20900. * If null the sub meshes will be render in the order they were created
  20901. */
  20902. set: function (value) {
  20903. if (value) {
  20904. this._transparentSortCompareFn = value;
  20905. }
  20906. else {
  20907. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20908. }
  20909. this._renderTransparent = this.renderTransparentSorted;
  20910. },
  20911. enumerable: true,
  20912. configurable: true
  20913. });
  20914. /**
  20915. * Render all the sub meshes contained in the group.
  20916. * @param customRenderFunction Used to override the default render behaviour of the group.
  20917. * @returns true if rendered some submeshes.
  20918. */
  20919. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20920. if (customRenderFunction) {
  20921. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20922. return;
  20923. }
  20924. var engine = this._scene.getEngine();
  20925. // Depth only
  20926. if (this._depthOnlySubMeshes.length !== 0) {
  20927. engine.setColorWrite(false);
  20928. this._renderAlphaTest(this._depthOnlySubMeshes);
  20929. engine.setColorWrite(true);
  20930. }
  20931. // Opaque
  20932. if (this._opaqueSubMeshes.length !== 0) {
  20933. this._renderOpaque(this._opaqueSubMeshes);
  20934. }
  20935. // Alpha test
  20936. if (this._alphaTestSubMeshes.length !== 0) {
  20937. this._renderAlphaTest(this._alphaTestSubMeshes);
  20938. }
  20939. var stencilState = engine.getStencilBuffer();
  20940. engine.setStencilBuffer(false);
  20941. // Sprites
  20942. if (renderSprites) {
  20943. this._renderSprites();
  20944. }
  20945. // Particles
  20946. if (renderParticles) {
  20947. this._renderParticles(activeMeshes);
  20948. }
  20949. if (this.onBeforeTransparentRendering) {
  20950. this.onBeforeTransparentRendering();
  20951. }
  20952. // Transparent
  20953. if (this._transparentSubMeshes.length !== 0) {
  20954. this._renderTransparent(this._transparentSubMeshes);
  20955. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20956. }
  20957. // Set back stencil to false in case it changes before the edge renderer.
  20958. engine.setStencilBuffer(false);
  20959. // Edges
  20960. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20961. this._edgesRenderers.data[edgesRendererIndex].render();
  20962. }
  20963. // Restore Stencil state.
  20964. engine.setStencilBuffer(stencilState);
  20965. };
  20966. /**
  20967. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20968. * @param subMeshes The submeshes to render
  20969. */
  20970. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20971. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20972. };
  20973. /**
  20974. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20975. * @param subMeshes The submeshes to render
  20976. */
  20977. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20978. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20979. };
  20980. /**
  20981. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20982. * @param subMeshes The submeshes to render
  20983. */
  20984. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20985. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20986. };
  20987. /**
  20988. * Renders the submeshes in a specified order.
  20989. * @param subMeshes The submeshes to sort before render
  20990. * @param sortCompareFn The comparison function use to sort
  20991. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20992. * @param transparent Specifies to activate blending if true
  20993. */
  20994. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20995. var subIndex = 0;
  20996. var subMesh;
  20997. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20998. for (; subIndex < subMeshes.length; subIndex++) {
  20999. subMesh = subMeshes.data[subIndex];
  21000. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21001. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21002. }
  21003. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21004. if (sortCompareFn) {
  21005. sortedArray.sort(sortCompareFn);
  21006. }
  21007. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21008. subMesh = sortedArray[subIndex];
  21009. if (transparent) {
  21010. var material = subMesh.getMaterial();
  21011. if (material && material.needDepthPrePass) {
  21012. var engine = material.getScene().getEngine();
  21013. engine.setColorWrite(false);
  21014. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21015. subMesh.render(false);
  21016. engine.setColorWrite(true);
  21017. }
  21018. }
  21019. subMesh.render(transparent);
  21020. }
  21021. };
  21022. /**
  21023. * Renders the submeshes in the order they were dispatched (no sort applied).
  21024. * @param subMeshes The submeshes to render
  21025. */
  21026. RenderingGroup.renderUnsorted = function (subMeshes) {
  21027. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21028. var submesh = subMeshes.data[subIndex];
  21029. submesh.render(false);
  21030. }
  21031. };
  21032. /**
  21033. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21034. * are rendered back to front if in the same alpha index.
  21035. *
  21036. * @param a The first submesh
  21037. * @param b The second submesh
  21038. * @returns The result of the comparison
  21039. */
  21040. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21041. // Alpha index first
  21042. if (a._alphaIndex > b._alphaIndex) {
  21043. return 1;
  21044. }
  21045. if (a._alphaIndex < b._alphaIndex) {
  21046. return -1;
  21047. }
  21048. // Then distance to camera
  21049. return RenderingGroup.backToFrontSortCompare(a, b);
  21050. };
  21051. /**
  21052. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21053. * are rendered back to front.
  21054. *
  21055. * @param a The first submesh
  21056. * @param b The second submesh
  21057. * @returns The result of the comparison
  21058. */
  21059. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21060. // Then distance to camera
  21061. if (a._distanceToCamera < b._distanceToCamera) {
  21062. return 1;
  21063. }
  21064. if (a._distanceToCamera > b._distanceToCamera) {
  21065. return -1;
  21066. }
  21067. return 0;
  21068. };
  21069. /**
  21070. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21071. * are rendered front to back (prevent overdraw).
  21072. *
  21073. * @param a The first submesh
  21074. * @param b The second submesh
  21075. * @returns The result of the comparison
  21076. */
  21077. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21078. // Then distance to camera
  21079. if (a._distanceToCamera < b._distanceToCamera) {
  21080. return -1;
  21081. }
  21082. if (a._distanceToCamera > b._distanceToCamera) {
  21083. return 1;
  21084. }
  21085. return 0;
  21086. };
  21087. /**
  21088. * Resets the different lists of submeshes to prepare a new frame.
  21089. */
  21090. RenderingGroup.prototype.prepare = function () {
  21091. this._opaqueSubMeshes.reset();
  21092. this._transparentSubMeshes.reset();
  21093. this._alphaTestSubMeshes.reset();
  21094. this._depthOnlySubMeshes.reset();
  21095. this._particleSystems.reset();
  21096. this._spriteManagers.reset();
  21097. this._edgesRenderers.reset();
  21098. };
  21099. RenderingGroup.prototype.dispose = function () {
  21100. this._opaqueSubMeshes.dispose();
  21101. this._transparentSubMeshes.dispose();
  21102. this._alphaTestSubMeshes.dispose();
  21103. this._depthOnlySubMeshes.dispose();
  21104. this._particleSystems.dispose();
  21105. this._spriteManagers.dispose();
  21106. this._edgesRenderers.dispose();
  21107. };
  21108. /**
  21109. * Inserts the submesh in its correct queue depending on its material.
  21110. * @param subMesh The submesh to dispatch
  21111. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21112. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21113. */
  21114. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21115. // Get mesh and materials if not provided
  21116. if (mesh === undefined) {
  21117. mesh = subMesh.getMesh();
  21118. }
  21119. if (material === undefined) {
  21120. material = subMesh.getMaterial();
  21121. }
  21122. if (material === null || material === undefined) {
  21123. return;
  21124. }
  21125. if (material.needAlphaBlendingForMesh(mesh)) {
  21126. this._transparentSubMeshes.push(subMesh);
  21127. }
  21128. else if (material.needAlphaTesting()) {
  21129. if (material.needDepthPrePass) {
  21130. this._depthOnlySubMeshes.push(subMesh);
  21131. }
  21132. this._alphaTestSubMeshes.push(subMesh);
  21133. }
  21134. else {
  21135. if (material.needDepthPrePass) {
  21136. this._depthOnlySubMeshes.push(subMesh);
  21137. }
  21138. this._opaqueSubMeshes.push(subMesh); // Opaque
  21139. }
  21140. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21141. this._edgesRenderers.push(mesh._edgesRenderer);
  21142. }
  21143. };
  21144. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21145. this._spriteManagers.push(spriteManager);
  21146. };
  21147. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21148. this._particleSystems.push(particleSystem);
  21149. };
  21150. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21151. if (this._particleSystems.length === 0) {
  21152. return;
  21153. }
  21154. // Particles
  21155. var activeCamera = this._scene.activeCamera;
  21156. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21157. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21158. var particleSystem = this._particleSystems.data[particleIndex];
  21159. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21160. continue;
  21161. }
  21162. var emitter = particleSystem.emitter;
  21163. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21164. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21165. }
  21166. }
  21167. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21168. };
  21169. RenderingGroup.prototype._renderSprites = function () {
  21170. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21171. return;
  21172. }
  21173. // Sprites
  21174. var activeCamera = this._scene.activeCamera;
  21175. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21176. for (var id = 0; id < this._spriteManagers.length; id++) {
  21177. var spriteManager = this._spriteManagers.data[id];
  21178. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21179. spriteManager.render();
  21180. }
  21181. }
  21182. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21183. };
  21184. return RenderingGroup;
  21185. }());
  21186. BABYLON.RenderingGroup = RenderingGroup;
  21187. })(BABYLON || (BABYLON = {}));
  21188. //# sourceMappingURL=babylon.renderingGroup.js.map
  21189. var BABYLON;
  21190. (function (BABYLON) {
  21191. var ClickInfo = /** @class */ (function () {
  21192. function ClickInfo() {
  21193. this._singleClick = false;
  21194. this._doubleClick = false;
  21195. this._hasSwiped = false;
  21196. this._ignore = false;
  21197. }
  21198. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21199. get: function () {
  21200. return this._singleClick;
  21201. },
  21202. set: function (b) {
  21203. this._singleClick = b;
  21204. },
  21205. enumerable: true,
  21206. configurable: true
  21207. });
  21208. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21209. get: function () {
  21210. return this._doubleClick;
  21211. },
  21212. set: function (b) {
  21213. this._doubleClick = b;
  21214. },
  21215. enumerable: true,
  21216. configurable: true
  21217. });
  21218. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21219. get: function () {
  21220. return this._hasSwiped;
  21221. },
  21222. set: function (b) {
  21223. this._hasSwiped = b;
  21224. },
  21225. enumerable: true,
  21226. configurable: true
  21227. });
  21228. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21229. get: function () {
  21230. return this._ignore;
  21231. },
  21232. set: function (b) {
  21233. this._ignore = b;
  21234. },
  21235. enumerable: true,
  21236. configurable: true
  21237. });
  21238. return ClickInfo;
  21239. }());
  21240. /**
  21241. * This class is used by the onRenderingGroupObservable
  21242. */
  21243. var RenderingGroupInfo = /** @class */ (function () {
  21244. function RenderingGroupInfo() {
  21245. }
  21246. /**
  21247. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21248. * This stage will be fired no matter what
  21249. */
  21250. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21251. /**
  21252. * Called before opaque object are rendered.
  21253. * This stage will be fired only if there's 3D Opaque content to render
  21254. */
  21255. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21256. /**
  21257. * Called after the opaque objects are rendered and before the transparent ones
  21258. * This stage will be fired only if there's 3D transparent content to render
  21259. */
  21260. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21261. /**
  21262. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21263. * This stage will be fired no matter what
  21264. */
  21265. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21266. return RenderingGroupInfo;
  21267. }());
  21268. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21269. /**
  21270. * Represents a scene to be rendered by the engine.
  21271. * @see http://doc.babylonjs.com/page.php?p=21911
  21272. */
  21273. var Scene = /** @class */ (function () {
  21274. /**
  21275. * @constructor
  21276. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21277. */
  21278. function Scene(engine) {
  21279. // Members
  21280. this.autoClear = true;
  21281. this.autoClearDepthAndStencil = true;
  21282. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21283. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21284. this.forceWireframe = false;
  21285. this._forcePointsCloud = false;
  21286. this.forceShowBoundingBoxes = false;
  21287. this.animationsEnabled = true;
  21288. this.useConstantAnimationDeltaTime = false;
  21289. this.constantlyUpdateMeshUnderPointer = false;
  21290. this.hoverCursor = "pointer";
  21291. this.defaultCursor = "";
  21292. /**
  21293. * This is used to call preventDefault() on pointer down
  21294. * in order to block unwanted artifacts like system double clicks
  21295. */
  21296. this.preventDefaultOnPointerDown = true;
  21297. // Metadata
  21298. this.metadata = null;
  21299. /**
  21300. * An event triggered when the scene is disposed.
  21301. * @type {BABYLON.Observable}
  21302. */
  21303. this.onDisposeObservable = new BABYLON.Observable();
  21304. /**
  21305. * An event triggered before rendering the scene (right after animations and physics)
  21306. * @type {BABYLON.Observable}
  21307. */
  21308. this.onBeforeRenderObservable = new BABYLON.Observable();
  21309. /**
  21310. * An event triggered after rendering the scene
  21311. * @type {BABYLON.Observable}
  21312. */
  21313. this.onAfterRenderObservable = new BABYLON.Observable();
  21314. /**
  21315. * An event triggered before animating the scene
  21316. * @type {BABYLON.Observable}
  21317. */
  21318. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21319. /**
  21320. * An event triggered after animations processing
  21321. * @type {BABYLON.Observable}
  21322. */
  21323. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21324. /**
  21325. * An event triggered before draw calls are ready to be sent
  21326. * @type {BABYLON.Observable}
  21327. */
  21328. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21329. /**
  21330. * An event triggered after draw calls have been sent
  21331. * @type {BABYLON.Observable}
  21332. */
  21333. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21334. /**
  21335. * An event triggered when physic simulation is about to be run
  21336. * @type {BABYLON.Observable}
  21337. */
  21338. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21339. /**
  21340. * An event triggered when physic simulation has been done
  21341. * @type {BABYLON.Observable}
  21342. */
  21343. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21344. /**
  21345. * An event triggered when the scene is ready
  21346. * @type {BABYLON.Observable}
  21347. */
  21348. this.onReadyObservable = new BABYLON.Observable();
  21349. /**
  21350. * An event triggered before rendering a camera
  21351. * @type {BABYLON.Observable}
  21352. */
  21353. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21354. /**
  21355. * An event triggered after rendering a camera
  21356. * @type {BABYLON.Observable}
  21357. */
  21358. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21359. /**
  21360. * An event triggered when active meshes evaluation is about to start
  21361. * @type {BABYLON.Observable}
  21362. */
  21363. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21364. /**
  21365. * An event triggered when active meshes evaluation is done
  21366. * @type {BABYLON.Observable}
  21367. */
  21368. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21369. /**
  21370. * An event triggered when particles rendering is about to start
  21371. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21372. * @type {BABYLON.Observable}
  21373. */
  21374. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21375. /**
  21376. * An event triggered when particles rendering is done
  21377. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21378. * @type {BABYLON.Observable}
  21379. */
  21380. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21381. /**
  21382. * An event triggered when sprites rendering is about to start
  21383. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21384. * @type {BABYLON.Observable}
  21385. */
  21386. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21387. /**
  21388. * An event triggered when sprites rendering is done
  21389. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21390. * @type {BABYLON.Observable}
  21391. */
  21392. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21393. /**
  21394. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21395. * @type {BABYLON.Observable}
  21396. */
  21397. this.onDataLoadedObservable = new BABYLON.Observable();
  21398. /**
  21399. * An event triggered when a camera is created
  21400. * @type {BABYLON.Observable}
  21401. */
  21402. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21403. /**
  21404. * An event triggered when a camera is removed
  21405. * @type {BABYLON.Observable}
  21406. */
  21407. this.onCameraRemovedObservable = new BABYLON.Observable();
  21408. /**
  21409. * An event triggered when a light is created
  21410. * @type {BABYLON.Observable}
  21411. */
  21412. this.onNewLightAddedObservable = new BABYLON.Observable();
  21413. /**
  21414. * An event triggered when a light is removed
  21415. * @type {BABYLON.Observable}
  21416. */
  21417. this.onLightRemovedObservable = new BABYLON.Observable();
  21418. /**
  21419. * An event triggered when a geometry is created
  21420. * @type {BABYLON.Observable}
  21421. */
  21422. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21423. /**
  21424. * An event triggered when a geometry is removed
  21425. * @type {BABYLON.Observable}
  21426. */
  21427. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21428. /**
  21429. * An event triggered when a transform node is created
  21430. * @type {BABYLON.Observable}
  21431. */
  21432. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21433. /**
  21434. * An event triggered when a transform node is removed
  21435. * @type {BABYLON.Observable}
  21436. */
  21437. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21438. /**
  21439. * An event triggered when a mesh is created
  21440. * @type {BABYLON.Observable}
  21441. */
  21442. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21443. /**
  21444. * An event triggered when a mesh is removed
  21445. * @type {BABYLON.Observable}
  21446. */
  21447. this.onMeshRemovedObservable = new BABYLON.Observable();
  21448. /**
  21449. * An event triggered when render targets are about to be rendered
  21450. * Can happen multiple times per frame.
  21451. * @type {BABYLON.Observable}
  21452. */
  21453. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21454. /**
  21455. * An event triggered when render targets were rendered.
  21456. * Can happen multiple times per frame.
  21457. * @type {BABYLON.Observable}
  21458. */
  21459. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21460. /**
  21461. * An event triggered before calculating deterministic simulation step
  21462. * @type {BABYLON.Observable}
  21463. */
  21464. this.onBeforeStepObservable = new BABYLON.Observable();
  21465. /**
  21466. * An event triggered after calculating deterministic simulation step
  21467. * @type {BABYLON.Observable}
  21468. */
  21469. this.onAfterStepObservable = new BABYLON.Observable();
  21470. /**
  21471. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21472. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21473. * 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)
  21474. */
  21475. this.onRenderingGroupObservable = new BABYLON.Observable();
  21476. // Animations
  21477. this.animations = [];
  21478. /**
  21479. * 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).
  21480. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21481. */
  21482. this.onPrePointerObservable = new BABYLON.Observable();
  21483. /**
  21484. * Observable event triggered each time an input event is received from the rendering canvas
  21485. */
  21486. this.onPointerObservable = new BABYLON.Observable();
  21487. this._meshPickProceed = false;
  21488. this._currentPickResult = null;
  21489. this._previousPickResult = null;
  21490. this._totalPointersPressed = 0;
  21491. this._doubleClickOccured = false;
  21492. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21493. this.cameraToUseForPointers = null;
  21494. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21495. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21496. this._startingPointerTime = 0;
  21497. this._previousStartingPointerTime = 0;
  21498. // Deterministic lockstep
  21499. this._timeAccumulator = 0;
  21500. this._currentStepId = 0;
  21501. this._currentInternalStep = 0;
  21502. // Keyboard
  21503. /**
  21504. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21505. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21506. */
  21507. this.onPreKeyboardObservable = new BABYLON.Observable();
  21508. /**
  21509. * Observable event triggered each time an keyboard event is received from the hosting window
  21510. */
  21511. this.onKeyboardObservable = new BABYLON.Observable();
  21512. // Coordinate system
  21513. /**
  21514. * use right-handed coordinate system on this scene.
  21515. * @type {boolean}
  21516. */
  21517. this._useRightHandedSystem = false;
  21518. // Fog
  21519. this._fogEnabled = true;
  21520. this._fogMode = Scene.FOGMODE_NONE;
  21521. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21522. this.fogDensity = 0.1;
  21523. this.fogStart = 0;
  21524. this.fogEnd = 1000.0;
  21525. // Lights
  21526. /**
  21527. * is shadow enabled on this scene.
  21528. * @type {boolean}
  21529. */
  21530. this._shadowsEnabled = true;
  21531. /**
  21532. * is light enabled on this scene.
  21533. * @type {boolean}
  21534. */
  21535. this._lightsEnabled = true;
  21536. /**
  21537. * All of the lights added to this scene.
  21538. * @see BABYLON.Light
  21539. * @type {BABYLON.Light[]}
  21540. */
  21541. this.lights = new Array();
  21542. // Cameras
  21543. /** All of the cameras added to this scene. */
  21544. this.cameras = new Array();
  21545. /** All of the active cameras added to this scene. */
  21546. this.activeCameras = new Array();
  21547. // Meshes
  21548. /**
  21549. * All of the tranform nodes added to this scene.
  21550. * @see BABYLON.TransformNode
  21551. * @type {BABYLON.TransformNode[]}
  21552. */
  21553. this.transformNodes = new Array();
  21554. /**
  21555. * All of the (abstract) meshes added to this scene.
  21556. * @see BABYLON.AbstractMesh
  21557. * @type {BABYLON.AbstractMesh[]}
  21558. */
  21559. this.meshes = new Array();
  21560. /**
  21561. * All of the animation groups added to this scene.
  21562. * @see BABYLON.AnimationGroup
  21563. * @type {BABYLON.AnimationGroup[]}
  21564. */
  21565. this.animationGroups = new Array();
  21566. // Geometries
  21567. this._geometries = new Array();
  21568. this.materials = new Array();
  21569. this.multiMaterials = new Array();
  21570. // Textures
  21571. this._texturesEnabled = true;
  21572. this.textures = new Array();
  21573. // Particles
  21574. this.particlesEnabled = true;
  21575. this.particleSystems = new Array();
  21576. // Sprites
  21577. this.spritesEnabled = true;
  21578. this.spriteManagers = new Array();
  21579. /**
  21580. * The list of layers (background and foreground) of the scene.
  21581. */
  21582. this.layers = new Array();
  21583. /**
  21584. * The list of effect layers (highlights/glow) contained in the scene.
  21585. */
  21586. this.effectLayers = new Array();
  21587. // Skeletons
  21588. this._skeletonsEnabled = true;
  21589. this.skeletons = new Array();
  21590. // Morph targets
  21591. this.morphTargetManagers = new Array();
  21592. // Lens flares
  21593. this.lensFlaresEnabled = true;
  21594. this.lensFlareSystems = new Array();
  21595. // Collisions
  21596. this.collisionsEnabled = true;
  21597. /** Defines the gravity applied to this scene */
  21598. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21599. // Postprocesses
  21600. this.postProcesses = new Array();
  21601. this.postProcessesEnabled = true;
  21602. // Customs render targets
  21603. this.renderTargetsEnabled = true;
  21604. this.dumpNextRenderTargets = false;
  21605. this.customRenderTargets = new Array();
  21606. // Imported meshes
  21607. this.importedMeshesFiles = new Array();
  21608. // Probes
  21609. this.probesEnabled = true;
  21610. this.reflectionProbes = new Array();
  21611. this._actionManagers = new Array();
  21612. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21613. // Procedural textures
  21614. this.proceduralTexturesEnabled = true;
  21615. this._proceduralTextures = new Array();
  21616. this.soundTracks = new Array();
  21617. this._audioEnabled = true;
  21618. this._headphone = false;
  21619. // Performance counters
  21620. this._totalVertices = new BABYLON.PerfCounter();
  21621. this._activeIndices = new BABYLON.PerfCounter();
  21622. this._activeParticles = new BABYLON.PerfCounter();
  21623. this._activeBones = new BABYLON.PerfCounter();
  21624. this._animationTime = 0;
  21625. this.animationTimeScale = 1;
  21626. this._renderId = 0;
  21627. this._executeWhenReadyTimeoutId = -1;
  21628. this._intermediateRendering = false;
  21629. this._viewUpdateFlag = -1;
  21630. this._projectionUpdateFlag = -1;
  21631. this._alternateViewUpdateFlag = -1;
  21632. this._alternateProjectionUpdateFlag = -1;
  21633. this._toBeDisposed = new BABYLON.SmartArray(256);
  21634. this._activeRequests = new Array();
  21635. this._pendingData = new Array();
  21636. this._isDisposed = false;
  21637. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21638. this._activeMeshes = new BABYLON.SmartArray(256);
  21639. this._processedMaterials = new BABYLON.SmartArray(256);
  21640. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21641. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21642. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21643. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21644. this._activeAnimatables = new Array();
  21645. this._transformMatrix = BABYLON.Matrix.Zero();
  21646. this._useAlternateCameraConfiguration = false;
  21647. this._alternateRendering = false;
  21648. this.requireLightSorting = false;
  21649. this._depthRenderer = {};
  21650. this._activeMeshesFrozen = false;
  21651. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21652. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21653. this._engine.scenes.push(this);
  21654. this._uid = null;
  21655. this._renderingManager = new BABYLON.RenderingManager(this);
  21656. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21657. if (BABYLON.OutlineRenderer) {
  21658. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21659. }
  21660. if (BABYLON.Tools.IsWindowObjectExist()) {
  21661. this.attachControl();
  21662. }
  21663. //simplification queue
  21664. if (BABYLON.SimplificationQueue) {
  21665. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21666. }
  21667. //collision coordinator initialization. For now legacy per default.
  21668. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21669. // Uniform Buffer
  21670. this._createUbo();
  21671. // Default Image processing definition.
  21672. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21673. }
  21674. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21675. /** The fog is deactivated */
  21676. get: function () {
  21677. return Scene._FOGMODE_NONE;
  21678. },
  21679. enumerable: true,
  21680. configurable: true
  21681. });
  21682. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21683. /** The fog density is following an exponential function */
  21684. get: function () {
  21685. return Scene._FOGMODE_EXP;
  21686. },
  21687. enumerable: true,
  21688. configurable: true
  21689. });
  21690. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21691. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21692. get: function () {
  21693. return Scene._FOGMODE_EXP2;
  21694. },
  21695. enumerable: true,
  21696. configurable: true
  21697. });
  21698. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21699. /** The fog density is following a linear function. */
  21700. get: function () {
  21701. return Scene._FOGMODE_LINEAR;
  21702. },
  21703. enumerable: true,
  21704. configurable: true
  21705. });
  21706. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21707. /**
  21708. * Texture used in all pbr material as the reflection texture.
  21709. * As in the majority of the scene they are the same (exception for multi room and so on),
  21710. * this is easier to reference from here than from all the materials.
  21711. */
  21712. get: function () {
  21713. return this._environmentTexture;
  21714. },
  21715. /**
  21716. * Texture used in all pbr material as the reflection texture.
  21717. * As in the majority of the scene they are the same (exception for multi room and so on),
  21718. * this is easier to set here than in all the materials.
  21719. */
  21720. set: function (value) {
  21721. if (this._environmentTexture === value) {
  21722. return;
  21723. }
  21724. this._environmentTexture = value;
  21725. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21726. },
  21727. enumerable: true,
  21728. configurable: true
  21729. });
  21730. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21731. /**
  21732. * Default image processing configuration used either in the rendering
  21733. * Forward main pass or through the imageProcessingPostProcess if present.
  21734. * As in the majority of the scene they are the same (exception for multi camera),
  21735. * this is easier to reference from here than from all the materials and post process.
  21736. *
  21737. * No setter as we it is a shared configuration, you can set the values instead.
  21738. */
  21739. get: function () {
  21740. return this._imageProcessingConfiguration;
  21741. },
  21742. enumerable: true,
  21743. configurable: true
  21744. });
  21745. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21746. get: function () {
  21747. return this._forcePointsCloud;
  21748. },
  21749. set: function (value) {
  21750. if (this._forcePointsCloud === value) {
  21751. return;
  21752. }
  21753. this._forcePointsCloud = value;
  21754. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21755. },
  21756. enumerable: true,
  21757. configurable: true
  21758. });
  21759. Object.defineProperty(Scene.prototype, "onDispose", {
  21760. /** A function to be executed when this scene is disposed. */
  21761. set: function (callback) {
  21762. if (this._onDisposeObserver) {
  21763. this.onDisposeObservable.remove(this._onDisposeObserver);
  21764. }
  21765. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21766. },
  21767. enumerable: true,
  21768. configurable: true
  21769. });
  21770. Object.defineProperty(Scene.prototype, "beforeRender", {
  21771. /** A function to be executed before rendering this scene */
  21772. set: function (callback) {
  21773. if (this._onBeforeRenderObserver) {
  21774. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21775. }
  21776. if (callback) {
  21777. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21778. }
  21779. },
  21780. enumerable: true,
  21781. configurable: true
  21782. });
  21783. Object.defineProperty(Scene.prototype, "afterRender", {
  21784. /** A function to be executed after rendering this scene */
  21785. set: function (callback) {
  21786. if (this._onAfterRenderObserver) {
  21787. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21788. }
  21789. if (callback) {
  21790. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21791. }
  21792. },
  21793. enumerable: true,
  21794. configurable: true
  21795. });
  21796. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21797. set: function (callback) {
  21798. if (this._onBeforeCameraRenderObserver) {
  21799. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21800. }
  21801. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21802. },
  21803. enumerable: true,
  21804. configurable: true
  21805. });
  21806. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21807. set: function (callback) {
  21808. if (this._onAfterCameraRenderObserver) {
  21809. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21810. }
  21811. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21812. },
  21813. enumerable: true,
  21814. configurable: true
  21815. });
  21816. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21817. get: function () {
  21818. if (!this._gamepadManager) {
  21819. this._gamepadManager = new BABYLON.GamepadManager(this);
  21820. }
  21821. return this._gamepadManager;
  21822. },
  21823. enumerable: true,
  21824. configurable: true
  21825. });
  21826. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21827. get: function () {
  21828. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21829. },
  21830. enumerable: true,
  21831. configurable: true
  21832. });
  21833. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21834. get: function () {
  21835. return this._useRightHandedSystem;
  21836. },
  21837. set: function (value) {
  21838. if (this._useRightHandedSystem === value) {
  21839. return;
  21840. }
  21841. this._useRightHandedSystem = value;
  21842. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21843. },
  21844. enumerable: true,
  21845. configurable: true
  21846. });
  21847. Scene.prototype.setStepId = function (newStepId) {
  21848. this._currentStepId = newStepId;
  21849. };
  21850. ;
  21851. Scene.prototype.getStepId = function () {
  21852. return this._currentStepId;
  21853. };
  21854. ;
  21855. Scene.prototype.getInternalStep = function () {
  21856. return this._currentInternalStep;
  21857. };
  21858. ;
  21859. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21860. get: function () {
  21861. return this._fogEnabled;
  21862. },
  21863. /**
  21864. * is fog enabled on this scene.
  21865. */
  21866. set: function (value) {
  21867. if (this._fogEnabled === value) {
  21868. return;
  21869. }
  21870. this._fogEnabled = value;
  21871. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21872. },
  21873. enumerable: true,
  21874. configurable: true
  21875. });
  21876. Object.defineProperty(Scene.prototype, "fogMode", {
  21877. get: function () {
  21878. return this._fogMode;
  21879. },
  21880. set: function (value) {
  21881. if (this._fogMode === value) {
  21882. return;
  21883. }
  21884. this._fogMode = value;
  21885. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21886. },
  21887. enumerable: true,
  21888. configurable: true
  21889. });
  21890. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21891. get: function () {
  21892. return this._shadowsEnabled;
  21893. },
  21894. set: function (value) {
  21895. if (this._shadowsEnabled === value) {
  21896. return;
  21897. }
  21898. this._shadowsEnabled = value;
  21899. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21900. },
  21901. enumerable: true,
  21902. configurable: true
  21903. });
  21904. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21905. get: function () {
  21906. return this._lightsEnabled;
  21907. },
  21908. set: function (value) {
  21909. if (this._lightsEnabled === value) {
  21910. return;
  21911. }
  21912. this._lightsEnabled = value;
  21913. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21914. },
  21915. enumerable: true,
  21916. configurable: true
  21917. });
  21918. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21919. /** The default material used on meshes when no material is affected */
  21920. get: function () {
  21921. if (!this._defaultMaterial) {
  21922. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21923. }
  21924. return this._defaultMaterial;
  21925. },
  21926. /** The default material used on meshes when no material is affected */
  21927. set: function (value) {
  21928. this._defaultMaterial = value;
  21929. },
  21930. enumerable: true,
  21931. configurable: true
  21932. });
  21933. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21934. get: function () {
  21935. return this._texturesEnabled;
  21936. },
  21937. set: function (value) {
  21938. if (this._texturesEnabled === value) {
  21939. return;
  21940. }
  21941. this._texturesEnabled = value;
  21942. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21943. },
  21944. enumerable: true,
  21945. configurable: true
  21946. });
  21947. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21948. get: function () {
  21949. return this._skeletonsEnabled;
  21950. },
  21951. set: function (value) {
  21952. if (this._skeletonsEnabled === value) {
  21953. return;
  21954. }
  21955. this._skeletonsEnabled = value;
  21956. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21957. },
  21958. enumerable: true,
  21959. configurable: true
  21960. });
  21961. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21962. get: function () {
  21963. if (!this._postProcessRenderPipelineManager) {
  21964. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21965. }
  21966. return this._postProcessRenderPipelineManager;
  21967. },
  21968. enumerable: true,
  21969. configurable: true
  21970. });
  21971. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21972. get: function () {
  21973. if (!this._mainSoundTrack) {
  21974. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21975. }
  21976. return this._mainSoundTrack;
  21977. },
  21978. enumerable: true,
  21979. configurable: true
  21980. });
  21981. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21982. get: function () {
  21983. return this._alternateRendering;
  21984. },
  21985. enumerable: true,
  21986. configurable: true
  21987. });
  21988. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21989. get: function () {
  21990. return this._frustumPlanes;
  21991. },
  21992. enumerable: true,
  21993. configurable: true
  21994. });
  21995. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21996. /**
  21997. * Gets the current geometry buffer associated to the scene.
  21998. */
  21999. get: function () {
  22000. return this._geometryBufferRenderer;
  22001. },
  22002. /**
  22003. * Sets the current geometry buffer for the scene.
  22004. */
  22005. set: function (geometryBufferRenderer) {
  22006. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22007. this._geometryBufferRenderer = geometryBufferRenderer;
  22008. }
  22009. },
  22010. enumerable: true,
  22011. configurable: true
  22012. });
  22013. Object.defineProperty(Scene.prototype, "debugLayer", {
  22014. // Properties
  22015. get: function () {
  22016. if (!this._debugLayer) {
  22017. this._debugLayer = new BABYLON.DebugLayer(this);
  22018. }
  22019. return this._debugLayer;
  22020. },
  22021. enumerable: true,
  22022. configurable: true
  22023. });
  22024. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22025. get: function () {
  22026. return this._workerCollisions;
  22027. },
  22028. set: function (enabled) {
  22029. if (!BABYLON.CollisionCoordinatorLegacy) {
  22030. return;
  22031. }
  22032. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22033. this._workerCollisions = enabled;
  22034. if (this.collisionCoordinator) {
  22035. this.collisionCoordinator.destroy();
  22036. }
  22037. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22038. this.collisionCoordinator.init(this);
  22039. },
  22040. enumerable: true,
  22041. configurable: true
  22042. });
  22043. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22044. get: function () {
  22045. return this._selectionOctree;
  22046. },
  22047. enumerable: true,
  22048. configurable: true
  22049. });
  22050. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22051. /**
  22052. * The mesh that is currently under the pointer.
  22053. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22054. */
  22055. get: function () {
  22056. return this._pointerOverMesh;
  22057. },
  22058. enumerable: true,
  22059. configurable: true
  22060. });
  22061. Object.defineProperty(Scene.prototype, "pointerX", {
  22062. /**
  22063. * Current on-screen X position of the pointer
  22064. * @return {number} X position of the pointer
  22065. */
  22066. get: function () {
  22067. return this._pointerX;
  22068. },
  22069. enumerable: true,
  22070. configurable: true
  22071. });
  22072. Object.defineProperty(Scene.prototype, "pointerY", {
  22073. /**
  22074. * Current on-screen Y position of the pointer
  22075. * @return {number} Y position of the pointer
  22076. */
  22077. get: function () {
  22078. return this._pointerY;
  22079. },
  22080. enumerable: true,
  22081. configurable: true
  22082. });
  22083. Scene.prototype.getCachedMaterial = function () {
  22084. return this._cachedMaterial;
  22085. };
  22086. Scene.prototype.getCachedEffect = function () {
  22087. return this._cachedEffect;
  22088. };
  22089. Scene.prototype.getCachedVisibility = function () {
  22090. return this._cachedVisibility;
  22091. };
  22092. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22093. if (visibility === void 0) { visibility = 1; }
  22094. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22095. };
  22096. Scene.prototype.getBoundingBoxRenderer = function () {
  22097. if (!this._boundingBoxRenderer) {
  22098. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22099. }
  22100. return this._boundingBoxRenderer;
  22101. };
  22102. Scene.prototype.getOutlineRenderer = function () {
  22103. return this._outlineRenderer;
  22104. };
  22105. Scene.prototype.getEngine = function () {
  22106. return this._engine;
  22107. };
  22108. Scene.prototype.getTotalVertices = function () {
  22109. return this._totalVertices.current;
  22110. };
  22111. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22112. get: function () {
  22113. return this._totalVertices;
  22114. },
  22115. enumerable: true,
  22116. configurable: true
  22117. });
  22118. Scene.prototype.getActiveIndices = function () {
  22119. return this._activeIndices.current;
  22120. };
  22121. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22122. get: function () {
  22123. return this._activeIndices;
  22124. },
  22125. enumerable: true,
  22126. configurable: true
  22127. });
  22128. Scene.prototype.getActiveParticles = function () {
  22129. return this._activeParticles.current;
  22130. };
  22131. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22132. get: function () {
  22133. return this._activeParticles;
  22134. },
  22135. enumerable: true,
  22136. configurable: true
  22137. });
  22138. Scene.prototype.getActiveBones = function () {
  22139. return this._activeBones.current;
  22140. };
  22141. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22142. get: function () {
  22143. return this._activeBones;
  22144. },
  22145. enumerable: true,
  22146. configurable: true
  22147. });
  22148. // Stats
  22149. Scene.prototype.getInterFramePerfCounter = function () {
  22150. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22151. return 0;
  22152. };
  22153. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22154. get: function () {
  22155. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22156. return null;
  22157. },
  22158. enumerable: true,
  22159. configurable: true
  22160. });
  22161. Scene.prototype.getLastFrameDuration = function () {
  22162. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22163. return 0;
  22164. };
  22165. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22166. get: function () {
  22167. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22168. return null;
  22169. },
  22170. enumerable: true,
  22171. configurable: true
  22172. });
  22173. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22174. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22175. return 0;
  22176. };
  22177. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22178. get: function () {
  22179. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22180. return null;
  22181. },
  22182. enumerable: true,
  22183. configurable: true
  22184. });
  22185. Scene.prototype.getActiveMeshes = function () {
  22186. return this._activeMeshes;
  22187. };
  22188. Scene.prototype.getRenderTargetsDuration = function () {
  22189. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22190. return 0;
  22191. };
  22192. Scene.prototype.getRenderDuration = function () {
  22193. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22194. return 0;
  22195. };
  22196. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22197. get: function () {
  22198. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22199. return null;
  22200. },
  22201. enumerable: true,
  22202. configurable: true
  22203. });
  22204. Scene.prototype.getParticlesDuration = function () {
  22205. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22206. return 0;
  22207. };
  22208. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22209. get: function () {
  22210. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22211. return null;
  22212. },
  22213. enumerable: true,
  22214. configurable: true
  22215. });
  22216. Scene.prototype.getSpritesDuration = function () {
  22217. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22218. return 0;
  22219. };
  22220. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22221. get: function () {
  22222. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22223. return null;
  22224. },
  22225. enumerable: true,
  22226. configurable: true
  22227. });
  22228. Scene.prototype.getAnimationRatio = function () {
  22229. return this._animationRatio;
  22230. };
  22231. Scene.prototype.getRenderId = function () {
  22232. return this._renderId;
  22233. };
  22234. Scene.prototype.incrementRenderId = function () {
  22235. this._renderId++;
  22236. };
  22237. Scene.prototype._updatePointerPosition = function (evt) {
  22238. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22239. if (!canvasRect) {
  22240. return;
  22241. }
  22242. this._pointerX = evt.clientX - canvasRect.left;
  22243. this._pointerY = evt.clientY - canvasRect.top;
  22244. this._unTranslatedPointerX = this._pointerX;
  22245. this._unTranslatedPointerY = this._pointerY;
  22246. };
  22247. Scene.prototype._createUbo = function () {
  22248. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22249. this._sceneUbo.addUniform("viewProjection", 16);
  22250. this._sceneUbo.addUniform("view", 16);
  22251. };
  22252. Scene.prototype._createAlternateUbo = function () {
  22253. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22254. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22255. this._alternateSceneUbo.addUniform("view", 16);
  22256. };
  22257. // Pointers handling
  22258. /**
  22259. * Use this method to simulate a pointer move on a mesh
  22260. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22261. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22262. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22263. */
  22264. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22265. var evt = new PointerEvent("pointermove", pointerEventInit);
  22266. return this._processPointerMove(pickResult, evt);
  22267. };
  22268. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22269. var canvas = this._engine.getRenderingCanvas();
  22270. if (!canvas) {
  22271. return this;
  22272. }
  22273. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22274. this.setPointerOverSprite(null);
  22275. this.setPointerOverMesh(pickResult.pickedMesh);
  22276. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22277. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22278. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22279. }
  22280. else {
  22281. canvas.style.cursor = this.hoverCursor;
  22282. }
  22283. }
  22284. else {
  22285. canvas.style.cursor = this.defaultCursor;
  22286. }
  22287. }
  22288. else {
  22289. this.setPointerOverMesh(null);
  22290. // Sprites
  22291. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22292. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22293. this.setPointerOverSprite(pickResult.pickedSprite);
  22294. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22295. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22296. }
  22297. else {
  22298. canvas.style.cursor = this.hoverCursor;
  22299. }
  22300. }
  22301. else {
  22302. this.setPointerOverSprite(null);
  22303. // Restore pointer
  22304. canvas.style.cursor = this.defaultCursor;
  22305. }
  22306. }
  22307. if (pickResult) {
  22308. if (this.onPointerMove) {
  22309. this.onPointerMove(evt, pickResult);
  22310. }
  22311. if (this.onPointerObservable.hasObservers()) {
  22312. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22313. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22314. this.onPointerObservable.notifyObservers(pi, type);
  22315. }
  22316. }
  22317. return this;
  22318. };
  22319. /**
  22320. * Use this method to simulate a pointer down on a mesh
  22321. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22322. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22323. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22324. */
  22325. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22326. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22327. return this._processPointerDown(pickResult, evt);
  22328. };
  22329. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22330. var _this = this;
  22331. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22332. this._pickedDownMesh = pickResult.pickedMesh;
  22333. var actionManager = pickResult.pickedMesh.actionManager;
  22334. if (actionManager) {
  22335. if (actionManager.hasPickTriggers) {
  22336. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22337. switch (evt.button) {
  22338. case 0:
  22339. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22340. break;
  22341. case 1:
  22342. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22343. break;
  22344. case 2:
  22345. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22346. break;
  22347. }
  22348. }
  22349. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22350. window.setTimeout(function () {
  22351. 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);
  22352. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22353. if (_this._totalPointersPressed !== 0 &&
  22354. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22355. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22356. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22357. _this._startingPointerTime = 0;
  22358. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22359. }
  22360. }
  22361. }, Scene.LongPressDelay);
  22362. }
  22363. }
  22364. }
  22365. if (pickResult) {
  22366. if (this.onPointerDown) {
  22367. this.onPointerDown(evt, pickResult);
  22368. }
  22369. if (this.onPointerObservable.hasObservers()) {
  22370. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22371. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22372. this.onPointerObservable.notifyObservers(pi, type);
  22373. }
  22374. }
  22375. return this;
  22376. };
  22377. /**
  22378. * Use this method to simulate a pointer up on a mesh
  22379. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22380. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22381. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22382. */
  22383. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22384. var evt = new PointerEvent("pointerup", pointerEventInit);
  22385. var clickInfo = new ClickInfo();
  22386. clickInfo.singleClick = true;
  22387. clickInfo.ignore = true;
  22388. return this._processPointerUp(pickResult, evt, clickInfo);
  22389. };
  22390. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22391. if (pickResult && pickResult && pickResult.pickedMesh) {
  22392. this._pickedUpMesh = pickResult.pickedMesh;
  22393. if (this._pickedDownMesh === this._pickedUpMesh) {
  22394. if (this.onPointerPick) {
  22395. this.onPointerPick(evt, pickResult);
  22396. }
  22397. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22398. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22399. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22400. this.onPointerObservable.notifyObservers(pi, type);
  22401. }
  22402. }
  22403. if (pickResult.pickedMesh.actionManager) {
  22404. if (clickInfo.ignore) {
  22405. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22406. }
  22407. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22408. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22409. }
  22410. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22411. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22412. }
  22413. }
  22414. }
  22415. if (this._pickedDownMesh &&
  22416. this._pickedDownMesh.actionManager &&
  22417. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22418. this._pickedDownMesh !== this._pickedUpMesh) {
  22419. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22420. }
  22421. if (this.onPointerUp) {
  22422. this.onPointerUp(evt, pickResult);
  22423. }
  22424. if (this.onPointerObservable.hasObservers()) {
  22425. if (!clickInfo.ignore) {
  22426. if (!clickInfo.hasSwiped) {
  22427. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22428. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22429. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22430. this.onPointerObservable.notifyObservers(pi, type);
  22431. }
  22432. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22433. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22434. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22435. this.onPointerObservable.notifyObservers(pi, type);
  22436. }
  22437. }
  22438. }
  22439. else {
  22440. var type = BABYLON.PointerEventTypes.POINTERUP;
  22441. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22442. this.onPointerObservable.notifyObservers(pi, type);
  22443. }
  22444. }
  22445. return this;
  22446. };
  22447. /**
  22448. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22449. * @param attachUp defines if you want to attach events to pointerup
  22450. * @param attachDown defines if you want to attach events to pointerdown
  22451. * @param attachMove defines if you want to attach events to pointermove
  22452. */
  22453. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22454. var _this = this;
  22455. if (attachUp === void 0) { attachUp = true; }
  22456. if (attachDown === void 0) { attachDown = true; }
  22457. if (attachMove === void 0) { attachMove = true; }
  22458. this._initActionManager = function (act, clickInfo) {
  22459. if (!_this._meshPickProceed) {
  22460. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22461. _this._currentPickResult = pickResult;
  22462. if (pickResult) {
  22463. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22464. }
  22465. _this._meshPickProceed = true;
  22466. }
  22467. return act;
  22468. };
  22469. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22470. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22471. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22472. btn !== _this._previousButtonPressed) {
  22473. _this._doubleClickOccured = false;
  22474. clickInfo.singleClick = true;
  22475. clickInfo.ignore = false;
  22476. cb(clickInfo, _this._currentPickResult);
  22477. }
  22478. };
  22479. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22480. var clickInfo = new ClickInfo();
  22481. _this._currentPickResult = null;
  22482. var act = null;
  22483. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22484. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22485. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22486. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22487. act = _this._initActionManager(act, clickInfo);
  22488. if (act)
  22489. checkPicking = act.hasPickTriggers;
  22490. }
  22491. if (checkPicking) {
  22492. var btn = evt.button;
  22493. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22494. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22495. if (!clickInfo.hasSwiped) {
  22496. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22497. if (!checkSingleClickImmediately) {
  22498. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22499. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22500. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22501. act = _this._initActionManager(act, clickInfo);
  22502. if (act)
  22503. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22504. }
  22505. }
  22506. if (checkSingleClickImmediately) {
  22507. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22508. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22509. btn !== _this._previousButtonPressed) {
  22510. clickInfo.singleClick = true;
  22511. cb(clickInfo, _this._currentPickResult);
  22512. }
  22513. }
  22514. else {
  22515. // wait that no double click has been raised during the double click delay
  22516. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22517. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22518. }
  22519. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22520. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22521. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22522. act = _this._initActionManager(act, clickInfo);
  22523. if (act)
  22524. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22525. }
  22526. if (checkDoubleClick) {
  22527. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22528. if (btn === _this._previousButtonPressed &&
  22529. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22530. !_this._doubleClickOccured) {
  22531. // pointer has not moved for 2 clicks, it's a double click
  22532. if (!clickInfo.hasSwiped &&
  22533. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22534. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22535. _this._previousStartingPointerTime = 0;
  22536. _this._doubleClickOccured = true;
  22537. clickInfo.doubleClick = true;
  22538. clickInfo.ignore = false;
  22539. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22540. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22541. }
  22542. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22543. cb(clickInfo, _this._currentPickResult);
  22544. }
  22545. else {
  22546. _this._doubleClickOccured = false;
  22547. _this._previousStartingPointerTime = _this._startingPointerTime;
  22548. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22549. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22550. _this._previousButtonPressed = btn;
  22551. if (Scene.ExclusiveDoubleClickMode) {
  22552. if (_this._previousDelayedSimpleClickTimeout) {
  22553. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22554. }
  22555. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22556. cb(clickInfo, _this._previousPickResult);
  22557. }
  22558. else {
  22559. cb(clickInfo, _this._currentPickResult);
  22560. }
  22561. }
  22562. }
  22563. else {
  22564. _this._doubleClickOccured = false;
  22565. _this._previousStartingPointerTime = _this._startingPointerTime;
  22566. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22567. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22568. _this._previousButtonPressed = btn;
  22569. }
  22570. }
  22571. }
  22572. }
  22573. clickInfo.ignore = true;
  22574. cb(clickInfo, _this._currentPickResult);
  22575. };
  22576. this._spritePredicate = function (sprite) {
  22577. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22578. };
  22579. this._onPointerMove = function (evt) {
  22580. _this._updatePointerPosition(evt);
  22581. // PreObservable support
  22582. if (_this.onPrePointerObservable.hasObservers()) {
  22583. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22584. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22585. _this.onPrePointerObservable.notifyObservers(pi, type);
  22586. if (pi.skipOnPointerObservable) {
  22587. return;
  22588. }
  22589. }
  22590. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22591. return;
  22592. }
  22593. if (!_this.pointerMovePredicate) {
  22594. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22595. }
  22596. // Meshes
  22597. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22598. _this._processPointerMove(pickResult, evt);
  22599. };
  22600. this._onPointerDown = function (evt) {
  22601. _this._totalPointersPressed++;
  22602. _this._pickedDownMesh = null;
  22603. _this._meshPickProceed = false;
  22604. _this._updatePointerPosition(evt);
  22605. if (_this.preventDefaultOnPointerDown && canvas) {
  22606. evt.preventDefault();
  22607. canvas.focus();
  22608. }
  22609. // PreObservable support
  22610. if (_this.onPrePointerObservable.hasObservers()) {
  22611. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22612. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22613. _this.onPrePointerObservable.notifyObservers(pi, type);
  22614. if (pi.skipOnPointerObservable) {
  22615. return;
  22616. }
  22617. }
  22618. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22619. return;
  22620. }
  22621. _this._startingPointerPosition.x = _this._pointerX;
  22622. _this._startingPointerPosition.y = _this._pointerY;
  22623. _this._startingPointerTime = new Date().getTime();
  22624. if (!_this.pointerDownPredicate) {
  22625. _this.pointerDownPredicate = function (mesh) {
  22626. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22627. };
  22628. }
  22629. // Meshes
  22630. _this._pickedDownMesh = null;
  22631. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22632. _this._processPointerDown(pickResult, evt);
  22633. // Sprites
  22634. _this._pickedDownSprite = null;
  22635. if (_this.spriteManagers.length > 0) {
  22636. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22637. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22638. if (pickResult.pickedSprite.actionManager) {
  22639. _this._pickedDownSprite = pickResult.pickedSprite;
  22640. switch (evt.button) {
  22641. case 0:
  22642. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22643. break;
  22644. case 1:
  22645. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22646. break;
  22647. case 2:
  22648. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22649. break;
  22650. }
  22651. if (pickResult.pickedSprite.actionManager) {
  22652. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22653. }
  22654. }
  22655. }
  22656. }
  22657. };
  22658. this._onPointerUp = function (evt) {
  22659. if (_this._totalPointersPressed === 0) {
  22660. return; // So we need to test it the pointer down was pressed before.
  22661. }
  22662. _this._totalPointersPressed--;
  22663. _this._pickedUpMesh = null;
  22664. _this._meshPickProceed = false;
  22665. _this._updatePointerPosition(evt);
  22666. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22667. // PreObservable support
  22668. if (_this.onPrePointerObservable.hasObservers()) {
  22669. if (!clickInfo.ignore) {
  22670. if (!clickInfo.hasSwiped) {
  22671. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22672. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22673. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22674. _this.onPrePointerObservable.notifyObservers(pi, type);
  22675. if (pi.skipOnPointerObservable) {
  22676. return;
  22677. }
  22678. }
  22679. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22680. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22681. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22682. _this.onPrePointerObservable.notifyObservers(pi, type);
  22683. if (pi.skipOnPointerObservable) {
  22684. return;
  22685. }
  22686. }
  22687. }
  22688. }
  22689. else {
  22690. var type = BABYLON.PointerEventTypes.POINTERUP;
  22691. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22692. _this.onPrePointerObservable.notifyObservers(pi, type);
  22693. if (pi.skipOnPointerObservable) {
  22694. return;
  22695. }
  22696. }
  22697. }
  22698. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22699. return;
  22700. }
  22701. if (!_this.pointerUpPredicate) {
  22702. _this.pointerUpPredicate = function (mesh) {
  22703. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22704. };
  22705. }
  22706. // Meshes
  22707. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22708. _this._initActionManager(null, clickInfo);
  22709. }
  22710. if (!pickResult) {
  22711. pickResult = _this._currentPickResult;
  22712. }
  22713. _this._processPointerUp(pickResult, evt, clickInfo);
  22714. // Sprites
  22715. if (_this.spriteManagers.length > 0) {
  22716. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22717. if (spritePickResult) {
  22718. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22719. if (spritePickResult.pickedSprite.actionManager) {
  22720. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22721. if (spritePickResult.pickedSprite.actionManager) {
  22722. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22723. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22724. }
  22725. }
  22726. }
  22727. }
  22728. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22729. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22730. }
  22731. }
  22732. }
  22733. _this._previousPickResult = _this._currentPickResult;
  22734. });
  22735. };
  22736. this._onKeyDown = function (evt) {
  22737. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22738. if (_this.onPreKeyboardObservable.hasObservers()) {
  22739. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22740. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22741. if (pi.skipOnPointerObservable) {
  22742. return;
  22743. }
  22744. }
  22745. if (_this.onKeyboardObservable.hasObservers()) {
  22746. var pi = new BABYLON.KeyboardInfo(type, evt);
  22747. _this.onKeyboardObservable.notifyObservers(pi, type);
  22748. }
  22749. if (_this.actionManager) {
  22750. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22751. }
  22752. };
  22753. this._onKeyUp = function (evt) {
  22754. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22755. if (_this.onPreKeyboardObservable.hasObservers()) {
  22756. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22757. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22758. if (pi.skipOnPointerObservable) {
  22759. return;
  22760. }
  22761. }
  22762. if (_this.onKeyboardObservable.hasObservers()) {
  22763. var pi = new BABYLON.KeyboardInfo(type, evt);
  22764. _this.onKeyboardObservable.notifyObservers(pi, type);
  22765. }
  22766. if (_this.actionManager) {
  22767. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22768. }
  22769. };
  22770. var engine = this.getEngine();
  22771. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22772. if (!canvas) {
  22773. return;
  22774. }
  22775. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22776. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22777. });
  22778. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22779. if (!canvas) {
  22780. return;
  22781. }
  22782. canvas.removeEventListener("keydown", _this._onKeyDown);
  22783. canvas.removeEventListener("keyup", _this._onKeyUp);
  22784. });
  22785. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22786. var canvas = this._engine.getRenderingCanvas();
  22787. if (!canvas) {
  22788. return;
  22789. }
  22790. if (attachMove) {
  22791. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22792. // Wheel
  22793. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22794. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22795. }
  22796. if (attachDown) {
  22797. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22798. }
  22799. if (attachUp) {
  22800. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22801. }
  22802. canvas.tabIndex = 1;
  22803. };
  22804. Scene.prototype.detachControl = function () {
  22805. var engine = this.getEngine();
  22806. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22807. var canvas = engine.getRenderingCanvas();
  22808. if (!canvas) {
  22809. return;
  22810. }
  22811. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22812. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22813. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22814. if (this._onCanvasBlurObserver) {
  22815. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22816. }
  22817. if (this._onCanvasFocusObserver) {
  22818. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22819. }
  22820. // Wheel
  22821. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22822. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22823. // Keyboard
  22824. canvas.removeEventListener("keydown", this._onKeyDown);
  22825. canvas.removeEventListener("keyup", this._onKeyUp);
  22826. // Observables
  22827. this.onKeyboardObservable.clear();
  22828. this.onPreKeyboardObservable.clear();
  22829. this.onPointerObservable.clear();
  22830. this.onPrePointerObservable.clear();
  22831. };
  22832. /**
  22833. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22834. * Delay loaded resources are not taking in account
  22835. * @return true if all required resources are ready
  22836. */
  22837. Scene.prototype.isReady = function () {
  22838. if (this._isDisposed) {
  22839. return false;
  22840. }
  22841. if (this._pendingData.length > 0) {
  22842. return false;
  22843. }
  22844. var index;
  22845. var engine = this.getEngine();
  22846. // Geometries
  22847. for (index = 0; index < this._geometries.length; index++) {
  22848. var geometry = this._geometries[index];
  22849. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22850. return false;
  22851. }
  22852. }
  22853. // Meshes
  22854. for (index = 0; index < this.meshes.length; index++) {
  22855. var mesh = this.meshes[index];
  22856. if (!mesh.isEnabled()) {
  22857. continue;
  22858. }
  22859. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22860. continue;
  22861. }
  22862. if (!mesh.isReady(true)) {
  22863. return false;
  22864. }
  22865. // Effect layers
  22866. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22867. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22868. var layer = _a[_i];
  22869. if (!layer.hasMesh(mesh)) {
  22870. continue;
  22871. }
  22872. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22873. var subMesh = _c[_b];
  22874. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22875. return false;
  22876. }
  22877. }
  22878. }
  22879. }
  22880. // Particles
  22881. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  22882. var particleSystem = _e[_d];
  22883. if (!particleSystem.isReady()) {
  22884. return false;
  22885. }
  22886. }
  22887. return true;
  22888. };
  22889. Scene.prototype.resetCachedMaterial = function () {
  22890. this._cachedMaterial = null;
  22891. this._cachedEffect = null;
  22892. this._cachedVisibility = null;
  22893. };
  22894. Scene.prototype.registerBeforeRender = function (func) {
  22895. this.onBeforeRenderObservable.add(func);
  22896. };
  22897. Scene.prototype.unregisterBeforeRender = function (func) {
  22898. this.onBeforeRenderObservable.removeCallback(func);
  22899. };
  22900. Scene.prototype.registerAfterRender = function (func) {
  22901. this.onAfterRenderObservable.add(func);
  22902. };
  22903. Scene.prototype.unregisterAfterRender = function (func) {
  22904. this.onAfterRenderObservable.removeCallback(func);
  22905. };
  22906. Scene.prototype._executeOnceBeforeRender = function (func) {
  22907. var _this = this;
  22908. var execFunc = function () {
  22909. func();
  22910. setTimeout(function () {
  22911. _this.unregisterBeforeRender(execFunc);
  22912. });
  22913. };
  22914. this.registerBeforeRender(execFunc);
  22915. };
  22916. /**
  22917. * The provided function will run before render once and will be disposed afterwards.
  22918. * A timeout delay can be provided so that the function will be executed in N ms.
  22919. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22920. * @param func The function to be executed.
  22921. * @param timeout optional delay in ms
  22922. */
  22923. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22924. var _this = this;
  22925. if (timeout !== undefined) {
  22926. setTimeout(function () {
  22927. _this._executeOnceBeforeRender(func);
  22928. }, timeout);
  22929. }
  22930. else {
  22931. this._executeOnceBeforeRender(func);
  22932. }
  22933. };
  22934. Scene.prototype._addPendingData = function (data) {
  22935. this._pendingData.push(data);
  22936. };
  22937. Scene.prototype._removePendingData = function (data) {
  22938. var wasLoading = this.isLoading;
  22939. var index = this._pendingData.indexOf(data);
  22940. if (index !== -1) {
  22941. this._pendingData.splice(index, 1);
  22942. }
  22943. if (wasLoading && !this.isLoading) {
  22944. this.onDataLoadedObservable.notifyObservers(this);
  22945. }
  22946. };
  22947. Scene.prototype.getWaitingItemsCount = function () {
  22948. return this._pendingData.length;
  22949. };
  22950. Object.defineProperty(Scene.prototype, "isLoading", {
  22951. get: function () {
  22952. return this._pendingData.length > 0;
  22953. },
  22954. enumerable: true,
  22955. configurable: true
  22956. });
  22957. /**
  22958. * Registers a function to be executed when the scene is ready.
  22959. * @param {Function} func - the function to be executed.
  22960. */
  22961. Scene.prototype.executeWhenReady = function (func) {
  22962. var _this = this;
  22963. this.onReadyObservable.add(func);
  22964. if (this._executeWhenReadyTimeoutId !== -1) {
  22965. return;
  22966. }
  22967. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22968. _this._checkIsReady();
  22969. }, 150);
  22970. };
  22971. /**
  22972. * Returns a promise that resolves when the scene is ready.
  22973. * @returns A promise that resolves when the scene is ready.
  22974. */
  22975. Scene.prototype.whenReadyAsync = function () {
  22976. var _this = this;
  22977. return new Promise(function (resolve) {
  22978. _this.executeWhenReady(function () {
  22979. resolve();
  22980. });
  22981. });
  22982. };
  22983. Scene.prototype._checkIsReady = function () {
  22984. var _this = this;
  22985. if (this.isReady()) {
  22986. this.onReadyObservable.notifyObservers(this);
  22987. this.onReadyObservable.clear();
  22988. this._executeWhenReadyTimeoutId = -1;
  22989. return;
  22990. }
  22991. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22992. _this._checkIsReady();
  22993. }, 150);
  22994. };
  22995. // Animations
  22996. /**
  22997. * Will start the animation sequence of a given target
  22998. * @param target - the target
  22999. * @param {number} from - from which frame should animation start
  23000. * @param {number} to - till which frame should animation run.
  23001. * @param {boolean} [loop] - should the animation loop
  23002. * @param {number} [speedRatio] - the speed in which to run the animation
  23003. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  23004. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  23005. * Returns {BABYLON.Animatable} the animatable object created for this animation
  23006. * See BABYLON.Animatable
  23007. */
  23008. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  23009. if (speedRatio === void 0) { speedRatio = 1.0; }
  23010. if (from > to && speedRatio > 0) {
  23011. speedRatio *= -1;
  23012. }
  23013. this.stopAnimation(target);
  23014. if (!animatable) {
  23015. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23016. }
  23017. // Local animations
  23018. if (target.animations) {
  23019. animatable.appendAnimations(target, target.animations);
  23020. }
  23021. // Children animations
  23022. if (target.getAnimatables) {
  23023. var animatables = target.getAnimatables();
  23024. for (var index = 0; index < animatables.length; index++) {
  23025. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  23026. }
  23027. }
  23028. animatable.reset();
  23029. return animatable;
  23030. };
  23031. /**
  23032. * Begin a new animation on a given node
  23033. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23034. * @param {BABYLON.Animation[]} defines the list of animations to start
  23035. * @param {number} from defines the initial value
  23036. * @param {number} to defines the final value
  23037. * @param {boolean} loop defines if you want animation to loop (off by default)
  23038. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23039. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23040. * @returns the list of created animatables
  23041. */
  23042. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23043. if (speedRatio === undefined) {
  23044. speedRatio = 1.0;
  23045. }
  23046. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23047. return animatable;
  23048. };
  23049. /**
  23050. * Begin a new animation on a given node and its hierarchy
  23051. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23052. * @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.
  23053. * @param {BABYLON.Animation[]} defines the list of animations to start
  23054. * @param {number} from defines the initial value
  23055. * @param {number} to defines the final value
  23056. * @param {boolean} loop defines if you want animation to loop (off by default)
  23057. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23058. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23059. * @returns the list of animatables created for all nodes
  23060. */
  23061. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23062. var children = target.getDescendants(directDescendantsOnly);
  23063. var result = [];
  23064. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23065. var child = children_1[_i];
  23066. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23067. }
  23068. return result;
  23069. };
  23070. Scene.prototype.getAnimatableByTarget = function (target) {
  23071. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23072. if (this._activeAnimatables[index].target === target) {
  23073. return this._activeAnimatables[index];
  23074. }
  23075. }
  23076. return null;
  23077. };
  23078. Object.defineProperty(Scene.prototype, "animatables", {
  23079. get: function () {
  23080. return this._activeAnimatables;
  23081. },
  23082. enumerable: true,
  23083. configurable: true
  23084. });
  23085. /**
  23086. * Will stop the animation of the given target
  23087. * @param target - the target
  23088. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23089. * @see beginAnimation
  23090. */
  23091. Scene.prototype.stopAnimation = function (target, animationName) {
  23092. var animatable = this.getAnimatableByTarget(target);
  23093. if (animatable) {
  23094. animatable.stop(animationName);
  23095. }
  23096. };
  23097. /**
  23098. * Stops and removes all animations that have been applied to the scene
  23099. */
  23100. Scene.prototype.stopAllAnimations = function () {
  23101. if (this._activeAnimatables) {
  23102. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23103. this._activeAnimatables[i].stop();
  23104. }
  23105. this._activeAnimatables = [];
  23106. }
  23107. };
  23108. Scene.prototype._animate = function () {
  23109. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23110. return;
  23111. }
  23112. // Getting time
  23113. var now = BABYLON.Tools.Now;
  23114. if (!this._animationTimeLast) {
  23115. if (this._pendingData.length > 0) {
  23116. return;
  23117. }
  23118. this._animationTimeLast = now;
  23119. }
  23120. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23121. this._animationTime += deltaTime;
  23122. this._animationTimeLast = now;
  23123. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23124. this._activeAnimatables[index]._animate(this._animationTime);
  23125. }
  23126. };
  23127. // Matrix
  23128. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23129. this._useAlternateCameraConfiguration = active;
  23130. };
  23131. Scene.prototype.getViewMatrix = function () {
  23132. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23133. };
  23134. Scene.prototype.getProjectionMatrix = function () {
  23135. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23136. };
  23137. Scene.prototype.getTransformMatrix = function () {
  23138. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23139. };
  23140. Scene.prototype.setTransformMatrix = function (view, projection) {
  23141. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23142. return;
  23143. }
  23144. this._viewUpdateFlag = view.updateFlag;
  23145. this._projectionUpdateFlag = projection.updateFlag;
  23146. this._viewMatrix = view;
  23147. this._projectionMatrix = projection;
  23148. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23149. // Update frustum
  23150. if (!this._frustumPlanes) {
  23151. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23152. }
  23153. else {
  23154. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23155. }
  23156. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23157. var otherCamera = this.activeCamera._alternateCamera;
  23158. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23159. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23160. }
  23161. if (this._sceneUbo.useUbo) {
  23162. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23163. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23164. this._sceneUbo.update();
  23165. }
  23166. };
  23167. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23168. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23169. return;
  23170. }
  23171. this._alternateViewUpdateFlag = view.updateFlag;
  23172. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23173. this._alternateViewMatrix = view;
  23174. this._alternateProjectionMatrix = projection;
  23175. if (!this._alternateTransformMatrix) {
  23176. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23177. }
  23178. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23179. if (!this._alternateSceneUbo) {
  23180. this._createAlternateUbo();
  23181. }
  23182. if (this._alternateSceneUbo.useUbo) {
  23183. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23184. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23185. this._alternateSceneUbo.update();
  23186. }
  23187. };
  23188. Scene.prototype.getSceneUniformBuffer = function () {
  23189. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23190. };
  23191. // Methods
  23192. Scene.prototype.getUniqueId = function () {
  23193. var result = Scene._uniqueIdCounter;
  23194. Scene._uniqueIdCounter++;
  23195. return result;
  23196. };
  23197. Scene.prototype.addMesh = function (newMesh) {
  23198. this.meshes.push(newMesh);
  23199. //notify the collision coordinator
  23200. if (this.collisionCoordinator) {
  23201. this.collisionCoordinator.onMeshAdded(newMesh);
  23202. }
  23203. newMesh._resyncLightSources();
  23204. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23205. };
  23206. Scene.prototype.removeMesh = function (toRemove) {
  23207. var index = this.meshes.indexOf(toRemove);
  23208. if (index !== -1) {
  23209. // Remove from the scene if mesh found
  23210. this.meshes.splice(index, 1);
  23211. }
  23212. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23213. return index;
  23214. };
  23215. Scene.prototype.addTransformNode = function (newTransformNode) {
  23216. this.transformNodes.push(newTransformNode);
  23217. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23218. };
  23219. Scene.prototype.removeTransformNode = function (toRemove) {
  23220. var index = this.transformNodes.indexOf(toRemove);
  23221. if (index !== -1) {
  23222. // Remove from the scene if found
  23223. this.transformNodes.splice(index, 1);
  23224. }
  23225. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23226. return index;
  23227. };
  23228. Scene.prototype.removeSkeleton = function (toRemove) {
  23229. var index = this.skeletons.indexOf(toRemove);
  23230. if (index !== -1) {
  23231. // Remove from the scene if found
  23232. this.skeletons.splice(index, 1);
  23233. }
  23234. return index;
  23235. };
  23236. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23237. var index = this.morphTargetManagers.indexOf(toRemove);
  23238. if (index !== -1) {
  23239. // Remove from the scene if found
  23240. this.morphTargetManagers.splice(index, 1);
  23241. }
  23242. return index;
  23243. };
  23244. Scene.prototype.removeLight = function (toRemove) {
  23245. var index = this.lights.indexOf(toRemove);
  23246. if (index !== -1) {
  23247. // Remove from meshes
  23248. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23249. var mesh = _a[_i];
  23250. mesh._removeLightSource(toRemove);
  23251. }
  23252. // Remove from the scene if mesh found
  23253. this.lights.splice(index, 1);
  23254. this.sortLightsByPriority();
  23255. }
  23256. this.onLightRemovedObservable.notifyObservers(toRemove);
  23257. return index;
  23258. };
  23259. Scene.prototype.removeCamera = function (toRemove) {
  23260. var index = this.cameras.indexOf(toRemove);
  23261. if (index !== -1) {
  23262. // Remove from the scene if mesh found
  23263. this.cameras.splice(index, 1);
  23264. }
  23265. // Remove from activeCameras
  23266. var index2 = this.activeCameras.indexOf(toRemove);
  23267. if (index2 !== -1) {
  23268. // Remove from the scene if mesh found
  23269. this.activeCameras.splice(index2, 1);
  23270. }
  23271. // Reset the activeCamera
  23272. if (this.activeCamera === toRemove) {
  23273. if (this.cameras.length > 0) {
  23274. this.activeCamera = this.cameras[0];
  23275. }
  23276. else {
  23277. this.activeCamera = null;
  23278. }
  23279. }
  23280. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23281. return index;
  23282. };
  23283. Scene.prototype.removeParticleSystem = function (toRemove) {
  23284. var index = this.particleSystems.indexOf(toRemove);
  23285. if (index !== -1) {
  23286. this.particleSystems.splice(index, 1);
  23287. }
  23288. return index;
  23289. };
  23290. ;
  23291. Scene.prototype.removeAnimation = function (toRemove) {
  23292. var index = this.animations.indexOf(toRemove);
  23293. if (index !== -1) {
  23294. this.animations.splice(index, 1);
  23295. }
  23296. return index;
  23297. };
  23298. ;
  23299. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23300. var index = this.multiMaterials.indexOf(toRemove);
  23301. if (index !== -1) {
  23302. this.multiMaterials.splice(index, 1);
  23303. }
  23304. return index;
  23305. };
  23306. ;
  23307. Scene.prototype.removeMaterial = function (toRemove) {
  23308. var index = this.materials.indexOf(toRemove);
  23309. if (index !== -1) {
  23310. this.materials.splice(index, 1);
  23311. }
  23312. return index;
  23313. };
  23314. ;
  23315. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23316. var index = this.lensFlareSystems.indexOf(toRemove);
  23317. if (index !== -1) {
  23318. this.lensFlareSystems.splice(index, 1);
  23319. }
  23320. return index;
  23321. };
  23322. ;
  23323. Scene.prototype.removeActionManager = function (toRemove) {
  23324. var index = this._actionManagers.indexOf(toRemove);
  23325. if (index !== -1) {
  23326. this._actionManagers.splice(index, 1);
  23327. }
  23328. return index;
  23329. };
  23330. ;
  23331. Scene.prototype.addLight = function (newLight) {
  23332. this.lights.push(newLight);
  23333. this.sortLightsByPriority();
  23334. // Add light to all meshes (To support if the light is removed and then readded)
  23335. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23336. var mesh = _a[_i];
  23337. if (mesh._lightSources.indexOf(newLight) === -1) {
  23338. mesh._lightSources.push(newLight);
  23339. mesh._resyncLightSources();
  23340. }
  23341. }
  23342. this.onNewLightAddedObservable.notifyObservers(newLight);
  23343. };
  23344. Scene.prototype.sortLightsByPriority = function () {
  23345. if (this.requireLightSorting) {
  23346. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23347. }
  23348. };
  23349. Scene.prototype.addCamera = function (newCamera) {
  23350. this.cameras.push(newCamera);
  23351. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23352. };
  23353. Scene.prototype.addSkeleton = function (newSkeleton) {
  23354. this.skeletons.push(newSkeleton);
  23355. };
  23356. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23357. this.particleSystems.push(newParticleSystem);
  23358. };
  23359. Scene.prototype.addAnimation = function (newAnimation) {
  23360. this.animations.push(newAnimation);
  23361. };
  23362. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23363. this.multiMaterials.push(newMultiMaterial);
  23364. };
  23365. Scene.prototype.addMaterial = function (newMaterial) {
  23366. this.materials.push(newMaterial);
  23367. };
  23368. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23369. this.morphTargetManagers.push(newMorphTargetManager);
  23370. };
  23371. Scene.prototype.addGeometry = function (newGeometrie) {
  23372. this._geometries.push(newGeometrie);
  23373. };
  23374. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23375. this.lensFlareSystems.push(newLensFlareSystem);
  23376. };
  23377. Scene.prototype.addActionManager = function (newActionManager) {
  23378. this._actionManagers.push(newActionManager);
  23379. };
  23380. /**
  23381. * Switch active camera
  23382. * @param {Camera} newCamera - new active camera
  23383. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23384. */
  23385. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23386. if (attachControl === void 0) { attachControl = true; }
  23387. var canvas = this._engine.getRenderingCanvas();
  23388. if (!canvas) {
  23389. return;
  23390. }
  23391. if (this.activeCamera) {
  23392. this.activeCamera.detachControl(canvas);
  23393. }
  23394. this.activeCamera = newCamera;
  23395. if (attachControl) {
  23396. newCamera.attachControl(canvas);
  23397. }
  23398. };
  23399. /**
  23400. * sets the active camera of the scene using its ID
  23401. * @param {string} id - the camera's ID
  23402. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23403. * @see activeCamera
  23404. */
  23405. Scene.prototype.setActiveCameraByID = function (id) {
  23406. var camera = this.getCameraByID(id);
  23407. if (camera) {
  23408. this.activeCamera = camera;
  23409. return camera;
  23410. }
  23411. return null;
  23412. };
  23413. /**
  23414. * sets the active camera of the scene using its name
  23415. * @param {string} name - the camera's name
  23416. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23417. * @see activeCamera
  23418. */
  23419. Scene.prototype.setActiveCameraByName = function (name) {
  23420. var camera = this.getCameraByName(name);
  23421. if (camera) {
  23422. this.activeCamera = camera;
  23423. return camera;
  23424. }
  23425. return null;
  23426. };
  23427. /**
  23428. * get an animation group using its name
  23429. * @param {string} the material's name
  23430. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23431. */
  23432. Scene.prototype.getAnimationGroupByName = function (name) {
  23433. for (var index = 0; index < this.animationGroups.length; index++) {
  23434. if (this.animationGroups[index].name === name) {
  23435. return this.animationGroups[index];
  23436. }
  23437. }
  23438. return null;
  23439. };
  23440. /**
  23441. * get a material using its id
  23442. * @param {string} the material's ID
  23443. * @return {BABYLON.Material|null} the material or null if none found.
  23444. */
  23445. Scene.prototype.getMaterialByID = function (id) {
  23446. for (var index = 0; index < this.materials.length; index++) {
  23447. if (this.materials[index].id === id) {
  23448. return this.materials[index];
  23449. }
  23450. }
  23451. return null;
  23452. };
  23453. /**
  23454. * get a material using its name
  23455. * @param {string} the material's name
  23456. * @return {BABYLON.Material|null} the material or null if none found.
  23457. */
  23458. Scene.prototype.getMaterialByName = function (name) {
  23459. for (var index = 0; index < this.materials.length; index++) {
  23460. if (this.materials[index].name === name) {
  23461. return this.materials[index];
  23462. }
  23463. }
  23464. return null;
  23465. };
  23466. Scene.prototype.getLensFlareSystemByName = function (name) {
  23467. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23468. if (this.lensFlareSystems[index].name === name) {
  23469. return this.lensFlareSystems[index];
  23470. }
  23471. }
  23472. return null;
  23473. };
  23474. Scene.prototype.getLensFlareSystemByID = function (id) {
  23475. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23476. if (this.lensFlareSystems[index].id === id) {
  23477. return this.lensFlareSystems[index];
  23478. }
  23479. }
  23480. return null;
  23481. };
  23482. Scene.prototype.getCameraByID = function (id) {
  23483. for (var index = 0; index < this.cameras.length; index++) {
  23484. if (this.cameras[index].id === id) {
  23485. return this.cameras[index];
  23486. }
  23487. }
  23488. return null;
  23489. };
  23490. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23491. for (var index = 0; index < this.cameras.length; index++) {
  23492. if (this.cameras[index].uniqueId === uniqueId) {
  23493. return this.cameras[index];
  23494. }
  23495. }
  23496. return null;
  23497. };
  23498. /**
  23499. * get a camera using its name
  23500. * @param {string} the camera's name
  23501. * @return {BABYLON.Camera|null} the camera or null if none found.
  23502. */
  23503. Scene.prototype.getCameraByName = function (name) {
  23504. for (var index = 0; index < this.cameras.length; index++) {
  23505. if (this.cameras[index].name === name) {
  23506. return this.cameras[index];
  23507. }
  23508. }
  23509. return null;
  23510. };
  23511. /**
  23512. * get a bone using its id
  23513. * @param {string} the bone's id
  23514. * @return {BABYLON.Bone|null} the bone or null if not found
  23515. */
  23516. Scene.prototype.getBoneByID = function (id) {
  23517. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23518. var skeleton = this.skeletons[skeletonIndex];
  23519. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23520. if (skeleton.bones[boneIndex].id === id) {
  23521. return skeleton.bones[boneIndex];
  23522. }
  23523. }
  23524. }
  23525. return null;
  23526. };
  23527. /**
  23528. * get a bone using its id
  23529. * @param {string} the bone's name
  23530. * @return {BABYLON.Bone|null} the bone or null if not found
  23531. */
  23532. Scene.prototype.getBoneByName = function (name) {
  23533. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23534. var skeleton = this.skeletons[skeletonIndex];
  23535. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23536. if (skeleton.bones[boneIndex].name === name) {
  23537. return skeleton.bones[boneIndex];
  23538. }
  23539. }
  23540. }
  23541. return null;
  23542. };
  23543. /**
  23544. * get a light node using its name
  23545. * @param {string} the light's name
  23546. * @return {BABYLON.Light|null} the light or null if none found.
  23547. */
  23548. Scene.prototype.getLightByName = function (name) {
  23549. for (var index = 0; index < this.lights.length; index++) {
  23550. if (this.lights[index].name === name) {
  23551. return this.lights[index];
  23552. }
  23553. }
  23554. return null;
  23555. };
  23556. /**
  23557. * get a light node using its ID
  23558. * @param {string} the light's id
  23559. * @return {BABYLON.Light|null} the light or null if none found.
  23560. */
  23561. Scene.prototype.getLightByID = function (id) {
  23562. for (var index = 0; index < this.lights.length; index++) {
  23563. if (this.lights[index].id === id) {
  23564. return this.lights[index];
  23565. }
  23566. }
  23567. return null;
  23568. };
  23569. /**
  23570. * get a light node using its scene-generated unique ID
  23571. * @param {number} the light's unique id
  23572. * @return {BABYLON.Light|null} the light or null if none found.
  23573. */
  23574. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23575. for (var index = 0; index < this.lights.length; index++) {
  23576. if (this.lights[index].uniqueId === uniqueId) {
  23577. return this.lights[index];
  23578. }
  23579. }
  23580. return null;
  23581. };
  23582. /**
  23583. * get a particle system by id
  23584. * @param id {number} the particle system id
  23585. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23586. */
  23587. Scene.prototype.getParticleSystemByID = function (id) {
  23588. for (var index = 0; index < this.particleSystems.length; index++) {
  23589. if (this.particleSystems[index].id === id) {
  23590. return this.particleSystems[index];
  23591. }
  23592. }
  23593. return null;
  23594. };
  23595. /**
  23596. * get a geometry using its ID
  23597. * @param {string} the geometry's id
  23598. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23599. */
  23600. Scene.prototype.getGeometryByID = function (id) {
  23601. for (var index = 0; index < this._geometries.length; index++) {
  23602. if (this._geometries[index].id === id) {
  23603. return this._geometries[index];
  23604. }
  23605. }
  23606. return null;
  23607. };
  23608. /**
  23609. * add a new geometry to this scene.
  23610. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23611. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23612. * @return {boolean} was the geometry added or not
  23613. */
  23614. Scene.prototype.pushGeometry = function (geometry, force) {
  23615. if (!force && this.getGeometryByID(geometry.id)) {
  23616. return false;
  23617. }
  23618. this._geometries.push(geometry);
  23619. //notify the collision coordinator
  23620. if (this.collisionCoordinator) {
  23621. this.collisionCoordinator.onGeometryAdded(geometry);
  23622. }
  23623. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23624. return true;
  23625. };
  23626. /**
  23627. * Removes an existing geometry
  23628. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23629. * @return {boolean} was the geometry removed or not
  23630. */
  23631. Scene.prototype.removeGeometry = function (geometry) {
  23632. var index = this._geometries.indexOf(geometry);
  23633. if (index > -1) {
  23634. this._geometries.splice(index, 1);
  23635. //notify the collision coordinator
  23636. if (this.collisionCoordinator) {
  23637. this.collisionCoordinator.onGeometryDeleted(geometry);
  23638. }
  23639. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23640. return true;
  23641. }
  23642. return false;
  23643. };
  23644. Scene.prototype.getGeometries = function () {
  23645. return this._geometries;
  23646. };
  23647. /**
  23648. * Get the first added mesh found of a given ID
  23649. * @param {string} id - the id to search for
  23650. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23651. */
  23652. Scene.prototype.getMeshByID = function (id) {
  23653. for (var index = 0; index < this.meshes.length; index++) {
  23654. if (this.meshes[index].id === id) {
  23655. return this.meshes[index];
  23656. }
  23657. }
  23658. return null;
  23659. };
  23660. Scene.prototype.getMeshesByID = function (id) {
  23661. return this.meshes.filter(function (m) {
  23662. return m.id === id;
  23663. });
  23664. };
  23665. /**
  23666. * Get the first added transform node found of a given ID
  23667. * @param {string} id - the id to search for
  23668. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23669. */
  23670. Scene.prototype.getTransformNodeByID = function (id) {
  23671. for (var index = 0; index < this.transformNodes.length; index++) {
  23672. if (this.transformNodes[index].id === id) {
  23673. return this.transformNodes[index];
  23674. }
  23675. }
  23676. return null;
  23677. };
  23678. Scene.prototype.getTransformNodesByID = function (id) {
  23679. return this.transformNodes.filter(function (m) {
  23680. return m.id === id;
  23681. });
  23682. };
  23683. /**
  23684. * Get a mesh with its auto-generated unique id
  23685. * @param {number} uniqueId - the unique id to search for
  23686. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23687. */
  23688. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23689. for (var index = 0; index < this.meshes.length; index++) {
  23690. if (this.meshes[index].uniqueId === uniqueId) {
  23691. return this.meshes[index];
  23692. }
  23693. }
  23694. return null;
  23695. };
  23696. /**
  23697. * Get a the last added mesh found of a given ID
  23698. * @param {string} id - the id to search for
  23699. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23700. */
  23701. Scene.prototype.getLastMeshByID = function (id) {
  23702. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23703. if (this.meshes[index].id === id) {
  23704. return this.meshes[index];
  23705. }
  23706. }
  23707. return null;
  23708. };
  23709. /**
  23710. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23711. * @param {string} id - the id to search for
  23712. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23713. */
  23714. Scene.prototype.getLastEntryByID = function (id) {
  23715. var index;
  23716. for (index = this.meshes.length - 1; index >= 0; index--) {
  23717. if (this.meshes[index].id === id) {
  23718. return this.meshes[index];
  23719. }
  23720. }
  23721. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23722. if (this.transformNodes[index].id === id) {
  23723. return this.transformNodes[index];
  23724. }
  23725. }
  23726. for (index = this.cameras.length - 1; index >= 0; index--) {
  23727. if (this.cameras[index].id === id) {
  23728. return this.cameras[index];
  23729. }
  23730. }
  23731. for (index = this.lights.length - 1; index >= 0; index--) {
  23732. if (this.lights[index].id === id) {
  23733. return this.lights[index];
  23734. }
  23735. }
  23736. return null;
  23737. };
  23738. Scene.prototype.getNodeByID = function (id) {
  23739. var mesh = this.getMeshByID(id);
  23740. if (mesh) {
  23741. return mesh;
  23742. }
  23743. var light = this.getLightByID(id);
  23744. if (light) {
  23745. return light;
  23746. }
  23747. var camera = this.getCameraByID(id);
  23748. if (camera) {
  23749. return camera;
  23750. }
  23751. var bone = this.getBoneByID(id);
  23752. return bone;
  23753. };
  23754. Scene.prototype.getNodeByName = function (name) {
  23755. var mesh = this.getMeshByName(name);
  23756. if (mesh) {
  23757. return mesh;
  23758. }
  23759. var light = this.getLightByName(name);
  23760. if (light) {
  23761. return light;
  23762. }
  23763. var camera = this.getCameraByName(name);
  23764. if (camera) {
  23765. return camera;
  23766. }
  23767. var bone = this.getBoneByName(name);
  23768. return bone;
  23769. };
  23770. Scene.prototype.getMeshByName = function (name) {
  23771. for (var index = 0; index < this.meshes.length; index++) {
  23772. if (this.meshes[index].name === name) {
  23773. return this.meshes[index];
  23774. }
  23775. }
  23776. return null;
  23777. };
  23778. Scene.prototype.getTransformNodeByName = function (name) {
  23779. for (var index = 0; index < this.transformNodes.length; index++) {
  23780. if (this.transformNodes[index].name === name) {
  23781. return this.transformNodes[index];
  23782. }
  23783. }
  23784. return null;
  23785. };
  23786. Scene.prototype.getSoundByName = function (name) {
  23787. var index;
  23788. if (BABYLON.AudioEngine) {
  23789. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23790. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23791. return this.mainSoundTrack.soundCollection[index];
  23792. }
  23793. }
  23794. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23795. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23796. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23797. return this.soundTracks[sdIndex].soundCollection[index];
  23798. }
  23799. }
  23800. }
  23801. }
  23802. return null;
  23803. };
  23804. Scene.prototype.getLastSkeletonByID = function (id) {
  23805. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23806. if (this.skeletons[index].id === id) {
  23807. return this.skeletons[index];
  23808. }
  23809. }
  23810. return null;
  23811. };
  23812. Scene.prototype.getSkeletonById = function (id) {
  23813. for (var index = 0; index < this.skeletons.length; index++) {
  23814. if (this.skeletons[index].id === id) {
  23815. return this.skeletons[index];
  23816. }
  23817. }
  23818. return null;
  23819. };
  23820. Scene.prototype.getSkeletonByName = function (name) {
  23821. for (var index = 0; index < this.skeletons.length; index++) {
  23822. if (this.skeletons[index].name === name) {
  23823. return this.skeletons[index];
  23824. }
  23825. }
  23826. return null;
  23827. };
  23828. Scene.prototype.getMorphTargetManagerById = function (id) {
  23829. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23830. if (this.morphTargetManagers[index].uniqueId === id) {
  23831. return this.morphTargetManagers[index];
  23832. }
  23833. }
  23834. return null;
  23835. };
  23836. Scene.prototype.isActiveMesh = function (mesh) {
  23837. return (this._activeMeshes.indexOf(mesh) !== -1);
  23838. };
  23839. /**
  23840. * Return a the first highlight layer of the scene with a given name.
  23841. * @param name The name of the highlight layer to look for.
  23842. * @return The highlight layer if found otherwise null.
  23843. */
  23844. Scene.prototype.getHighlightLayerByName = function (name) {
  23845. for (var index = 0; index < this.effectLayers.length; index++) {
  23846. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23847. return this.effectLayers[index];
  23848. }
  23849. }
  23850. return null;
  23851. };
  23852. /**
  23853. * Return a the first highlight layer of the scene with a given name.
  23854. * @param name The name of the highlight layer to look for.
  23855. * @return The highlight layer if found otherwise null.
  23856. */
  23857. Scene.prototype.getGlowLayerByName = function (name) {
  23858. for (var index = 0; index < this.effectLayers.length; index++) {
  23859. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23860. return this.effectLayers[index];
  23861. }
  23862. }
  23863. return null;
  23864. };
  23865. Object.defineProperty(Scene.prototype, "uid", {
  23866. /**
  23867. * Return a unique id as a string which can serve as an identifier for the scene
  23868. */
  23869. get: function () {
  23870. if (!this._uid) {
  23871. this._uid = BABYLON.Tools.RandomId();
  23872. }
  23873. return this._uid;
  23874. },
  23875. enumerable: true,
  23876. configurable: true
  23877. });
  23878. /**
  23879. * Add an externaly attached data from its key.
  23880. * This method call will fail and return false, if such key already exists.
  23881. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23882. * @param key the unique key that identifies the data
  23883. * @param data the data object to associate to the key for this Engine instance
  23884. * @return true if no such key were already present and the data was added successfully, false otherwise
  23885. */
  23886. Scene.prototype.addExternalData = function (key, data) {
  23887. if (!this._externalData) {
  23888. this._externalData = new BABYLON.StringDictionary();
  23889. }
  23890. return this._externalData.add(key, data);
  23891. };
  23892. /**
  23893. * Get an externaly attached data from its key
  23894. * @param key the unique key that identifies the data
  23895. * @return the associated data, if present (can be null), or undefined if not present
  23896. */
  23897. Scene.prototype.getExternalData = function (key) {
  23898. if (!this._externalData) {
  23899. return null;
  23900. }
  23901. return this._externalData.get(key);
  23902. };
  23903. /**
  23904. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23905. * @param key the unique key that identifies the data
  23906. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23907. * @return the associated data, can be null if the factory returned null.
  23908. */
  23909. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23910. if (!this._externalData) {
  23911. this._externalData = new BABYLON.StringDictionary();
  23912. }
  23913. return this._externalData.getOrAddWithFactory(key, factory);
  23914. };
  23915. /**
  23916. * Remove an externaly attached data from the Engine instance
  23917. * @param key the unique key that identifies the data
  23918. * @return true if the data was successfully removed, false if it doesn't exist
  23919. */
  23920. Scene.prototype.removeExternalData = function (key) {
  23921. return this._externalData.remove(key);
  23922. };
  23923. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23924. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23925. if (mesh.showSubMeshesBoundingBox) {
  23926. var boundingInfo = subMesh.getBoundingInfo();
  23927. if (boundingInfo !== null && boundingInfo !== undefined) {
  23928. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23929. }
  23930. }
  23931. var material = subMesh.getMaterial();
  23932. if (material !== null && material !== undefined) {
  23933. // Render targets
  23934. if (material.getRenderTargetTextures !== undefined) {
  23935. if (this._processedMaterials.indexOf(material) === -1) {
  23936. this._processedMaterials.push(material);
  23937. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23938. }
  23939. }
  23940. // Dispatch
  23941. this._activeIndices.addCount(subMesh.indexCount, false);
  23942. this._renderingManager.dispatch(subMesh, mesh, material);
  23943. }
  23944. }
  23945. };
  23946. /**
  23947. * Clear the processed materials smart array preventing retention point in material dispose.
  23948. */
  23949. Scene.prototype.freeProcessedMaterials = function () {
  23950. this._processedMaterials.dispose();
  23951. };
  23952. /**
  23953. * Clear the active meshes smart array preventing retention point in mesh dispose.
  23954. */
  23955. Scene.prototype.freeActiveMeshes = function () {
  23956. this._activeMeshes.dispose();
  23957. if (this.activeCamera && this.activeCamera._activeMeshes) {
  23958. this.activeCamera._activeMeshes.dispose();
  23959. }
  23960. if (this.activeCameras) {
  23961. for (var i = 0; i < this.activeCameras.length; i++) {
  23962. var activeCamera = this.activeCameras[i];
  23963. if (activeCamera && activeCamera._activeMeshes) {
  23964. activeCamera._activeMeshes.dispose();
  23965. }
  23966. }
  23967. }
  23968. };
  23969. /**
  23970. * Clear the info related to rendering groups preventing retention points during dispose.
  23971. */
  23972. Scene.prototype.freeRenderingGroups = function () {
  23973. if (this._renderingManager) {
  23974. this._renderingManager.freeRenderingGroups();
  23975. }
  23976. if (this.textures) {
  23977. for (var i = 0; i < this.textures.length; i++) {
  23978. var texture = this.textures[i];
  23979. if (texture && texture.renderList) {
  23980. texture.freeRenderingGroups();
  23981. }
  23982. }
  23983. }
  23984. };
  23985. Scene.prototype._isInIntermediateRendering = function () {
  23986. return this._intermediateRendering;
  23987. };
  23988. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23989. this._activeMeshCandidateProvider = provider;
  23990. };
  23991. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23992. return this._activeMeshCandidateProvider;
  23993. };
  23994. /**
  23995. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23996. */
  23997. Scene.prototype.freezeActiveMeshes = function () {
  23998. if (!this.activeCamera) {
  23999. return this;
  24000. }
  24001. if (!this._frustumPlanes) {
  24002. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24003. }
  24004. this._evaluateActiveMeshes();
  24005. this._activeMeshesFrozen = true;
  24006. return this;
  24007. };
  24008. /**
  24009. * Use this function to restart evaluating active meshes on every frame
  24010. */
  24011. Scene.prototype.unfreezeActiveMeshes = function () {
  24012. this._activeMeshesFrozen = false;
  24013. return this;
  24014. };
  24015. Scene.prototype._evaluateActiveMeshes = function () {
  24016. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24017. return;
  24018. }
  24019. if (!this.activeCamera) {
  24020. return;
  24021. }
  24022. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24023. this.activeCamera._activeMeshes.reset();
  24024. this._activeMeshes.reset();
  24025. this._renderingManager.reset();
  24026. this._processedMaterials.reset();
  24027. this._activeParticleSystems.reset();
  24028. this._activeSkeletons.reset();
  24029. this._softwareSkinnedMeshes.reset();
  24030. if (this._boundingBoxRenderer) {
  24031. this._boundingBoxRenderer.reset();
  24032. }
  24033. // Meshes
  24034. var meshes;
  24035. var len;
  24036. var checkIsEnabled = true;
  24037. // Determine mesh candidates
  24038. if (this._activeMeshCandidateProvider !== undefined) {
  24039. // Use _activeMeshCandidateProvider
  24040. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24041. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24042. if (meshes !== undefined) {
  24043. len = meshes.length;
  24044. }
  24045. else {
  24046. len = 0;
  24047. }
  24048. }
  24049. else if (this._selectionOctree !== undefined) {
  24050. // Octree
  24051. var selection = this._selectionOctree.select(this._frustumPlanes);
  24052. meshes = selection.data;
  24053. len = selection.length;
  24054. }
  24055. else {
  24056. // Full scene traversal
  24057. len = this.meshes.length;
  24058. meshes = this.meshes;
  24059. }
  24060. // Check each mesh
  24061. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24062. mesh = meshes[meshIndex];
  24063. if (mesh.isBlocked) {
  24064. continue;
  24065. }
  24066. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24067. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24068. continue;
  24069. }
  24070. mesh.computeWorldMatrix();
  24071. // Intersections
  24072. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24073. this._meshesForIntersections.pushNoDuplicate(mesh);
  24074. }
  24075. // Switch to current LOD
  24076. meshLOD = mesh.getLOD(this.activeCamera);
  24077. if (meshLOD === undefined || meshLOD === null) {
  24078. continue;
  24079. }
  24080. mesh._preActivate();
  24081. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24082. this._activeMeshes.push(mesh);
  24083. this.activeCamera._activeMeshes.push(mesh);
  24084. mesh._activate(this._renderId);
  24085. if (meshLOD !== mesh) {
  24086. meshLOD._activate(this._renderId);
  24087. }
  24088. this._activeMesh(mesh, meshLOD);
  24089. }
  24090. }
  24091. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24092. // Particle systems
  24093. if (this.particlesEnabled) {
  24094. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24095. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24096. var particleSystem = this.particleSystems[particleIndex];
  24097. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24098. continue;
  24099. }
  24100. var emitter = particleSystem.emitter;
  24101. if (!emitter.position || emitter.isEnabled()) {
  24102. this._activeParticleSystems.push(particleSystem);
  24103. particleSystem.animate();
  24104. this._renderingManager.dispatchParticles(particleSystem);
  24105. }
  24106. }
  24107. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24108. }
  24109. };
  24110. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24111. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24112. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24113. mesh.skeleton.prepare();
  24114. }
  24115. if (!mesh.computeBonesUsingShaders) {
  24116. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24117. }
  24118. }
  24119. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24120. var boundingInfo = sourceMesh.getBoundingInfo();
  24121. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24122. }
  24123. if (mesh !== undefined && mesh !== null
  24124. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24125. // Submeshes Octrees
  24126. var len;
  24127. var subMeshes;
  24128. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24129. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24130. len = intersections.length;
  24131. subMeshes = intersections.data;
  24132. }
  24133. else {
  24134. subMeshes = mesh.subMeshes;
  24135. len = subMeshes.length;
  24136. }
  24137. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24138. subMesh = subMeshes[subIndex];
  24139. this._evaluateSubMesh(subMesh, mesh);
  24140. }
  24141. }
  24142. };
  24143. Scene.prototype.updateTransformMatrix = function (force) {
  24144. if (!this.activeCamera) {
  24145. return;
  24146. }
  24147. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24148. };
  24149. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24150. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24151. };
  24152. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24153. if (camera && camera._skipRendering) {
  24154. return;
  24155. }
  24156. var engine = this._engine;
  24157. this.activeCamera = camera;
  24158. if (!this.activeCamera)
  24159. throw new Error("Active camera not set");
  24160. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24161. // Viewport
  24162. engine.setViewport(this.activeCamera.viewport);
  24163. // Camera
  24164. this.resetCachedMaterial();
  24165. this._renderId++;
  24166. this.updateTransformMatrix();
  24167. if (camera._alternateCamera) {
  24168. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24169. this._alternateRendering = true;
  24170. }
  24171. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24172. // Meshes
  24173. this._evaluateActiveMeshes();
  24174. // Software skinning
  24175. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24176. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24177. mesh.applySkeleton(mesh.skeleton);
  24178. }
  24179. // Render targets
  24180. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24181. var needsRestoreFrameBuffer = false;
  24182. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24183. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24184. }
  24185. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24186. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24187. }
  24188. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24189. this._intermediateRendering = true;
  24190. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24191. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24192. var renderTarget = this._renderTargets.data[renderIndex];
  24193. if (renderTarget._shouldRender()) {
  24194. this._renderId++;
  24195. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24196. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24197. }
  24198. }
  24199. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24200. this._intermediateRendering = false;
  24201. this._renderId++;
  24202. needsRestoreFrameBuffer = true; // Restore back buffer
  24203. }
  24204. // Render EffecttLayer Texture
  24205. var stencilState = this._engine.getStencilBuffer();
  24206. var renderEffects = false;
  24207. var needStencil = false;
  24208. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24209. this._intermediateRendering = true;
  24210. for (var i = 0; i < this.effectLayers.length; i++) {
  24211. var effectLayer = this.effectLayers[i];
  24212. if (effectLayer.shouldRender() &&
  24213. (!effectLayer.camera ||
  24214. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24215. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24216. renderEffects = true;
  24217. needStencil = needStencil || effectLayer.needStencil();
  24218. var renderTarget = effectLayer._mainTexture;
  24219. if (renderTarget._shouldRender()) {
  24220. this._renderId++;
  24221. renderTarget.render(false, false);
  24222. needsRestoreFrameBuffer = true;
  24223. }
  24224. }
  24225. }
  24226. this._intermediateRendering = false;
  24227. this._renderId++;
  24228. }
  24229. if (needsRestoreFrameBuffer) {
  24230. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24231. }
  24232. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24233. // Prepare Frame
  24234. this.postProcessManager._prepareFrame();
  24235. // Backgrounds
  24236. var layerIndex;
  24237. var layer;
  24238. if (this.layers.length) {
  24239. engine.setDepthBuffer(false);
  24240. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24241. layer = this.layers[layerIndex];
  24242. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24243. layer.render();
  24244. }
  24245. }
  24246. engine.setDepthBuffer(true);
  24247. }
  24248. // Activate effect Layer stencil
  24249. if (needStencil) {
  24250. this._engine.setStencilBuffer(true);
  24251. }
  24252. // Render
  24253. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24254. this._renderingManager.render(null, null, true, true);
  24255. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24256. // Restore effect Layer stencil
  24257. if (needStencil) {
  24258. this._engine.setStencilBuffer(stencilState);
  24259. }
  24260. // Bounding boxes
  24261. if (this._boundingBoxRenderer) {
  24262. this._boundingBoxRenderer.render();
  24263. }
  24264. // Lens flares
  24265. if (this.lensFlaresEnabled) {
  24266. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24267. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24268. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24269. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24270. lensFlareSystem.render();
  24271. }
  24272. }
  24273. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24274. }
  24275. // Foregrounds
  24276. if (this.layers.length) {
  24277. engine.setDepthBuffer(false);
  24278. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24279. layer = this.layers[layerIndex];
  24280. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24281. layer.render();
  24282. }
  24283. }
  24284. engine.setDepthBuffer(true);
  24285. }
  24286. // Effect Layer
  24287. if (renderEffects) {
  24288. engine.setDepthBuffer(false);
  24289. for (var i = 0; i < this.effectLayers.length; i++) {
  24290. if (this.effectLayers[i].shouldRender()) {
  24291. this.effectLayers[i].render();
  24292. }
  24293. }
  24294. engine.setDepthBuffer(true);
  24295. }
  24296. // Finalize frame
  24297. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24298. // Reset some special arrays
  24299. this._renderTargets.reset();
  24300. this._alternateRendering = false;
  24301. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24302. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24303. };
  24304. Scene.prototype._processSubCameras = function (camera) {
  24305. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24306. this._renderForCamera(camera);
  24307. return;
  24308. }
  24309. // rig cameras
  24310. for (var index = 0; index < camera._rigCameras.length; index++) {
  24311. this._renderForCamera(camera._rigCameras[index], camera);
  24312. }
  24313. this.activeCamera = camera;
  24314. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24315. };
  24316. Scene.prototype._checkIntersections = function () {
  24317. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24318. var sourceMesh = this._meshesForIntersections.data[index];
  24319. if (!sourceMesh.actionManager) {
  24320. continue;
  24321. }
  24322. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24323. var action = sourceMesh.actionManager.actions[actionIndex];
  24324. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24325. var parameters = action.getTriggerParameter();
  24326. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24327. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24328. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24329. if (areIntersecting && currentIntersectionInProgress === -1) {
  24330. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24331. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24332. sourceMesh._intersectionsInProgress.push(otherMesh);
  24333. }
  24334. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24335. sourceMesh._intersectionsInProgress.push(otherMesh);
  24336. }
  24337. }
  24338. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24339. //They intersected, and now they don't.
  24340. //is this trigger an exit trigger? execute an event.
  24341. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24342. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24343. }
  24344. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24345. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24346. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24347. }
  24348. }
  24349. }
  24350. }
  24351. }
  24352. };
  24353. Scene.prototype.render = function () {
  24354. if (this.isDisposed) {
  24355. return;
  24356. }
  24357. this._activeParticles.fetchNewFrame();
  24358. this._totalVertices.fetchNewFrame();
  24359. this._activeIndices.fetchNewFrame();
  24360. this._activeBones.fetchNewFrame();
  24361. this._meshesForIntersections.reset();
  24362. this.resetCachedMaterial();
  24363. this.onBeforeAnimationsObservable.notifyObservers(this);
  24364. // Actions
  24365. if (this.actionManager) {
  24366. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24367. }
  24368. //Simplification Queue
  24369. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24370. this.simplificationQueue.executeNext();
  24371. }
  24372. if (this._engine.isDeterministicLockStep()) {
  24373. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24374. var defaultFPS = (60.0 / 1000.0);
  24375. var defaultFrameTime = 1000 / 60; // frame time in MS
  24376. if (this._physicsEngine) {
  24377. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24378. }
  24379. var stepsTaken = 0;
  24380. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24381. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24382. internalSteps = Math.min(internalSteps, maxSubSteps);
  24383. do {
  24384. this.onBeforeStepObservable.notifyObservers(this);
  24385. // Animations
  24386. this._animationRatio = defaultFrameTime * defaultFPS;
  24387. this._animate();
  24388. this.onAfterAnimationsObservable.notifyObservers(this);
  24389. // Physics
  24390. if (this._physicsEngine) {
  24391. this.onBeforePhysicsObservable.notifyObservers(this);
  24392. this._physicsEngine._step(defaultFrameTime / 1000);
  24393. this.onAfterPhysicsObservable.notifyObservers(this);
  24394. }
  24395. this.onAfterStepObservable.notifyObservers(this);
  24396. this._currentStepId++;
  24397. stepsTaken++;
  24398. deltaTime -= defaultFrameTime;
  24399. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24400. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24401. }
  24402. else {
  24403. // Animations
  24404. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24405. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24406. this._animate();
  24407. this.onAfterAnimationsObservable.notifyObservers(this);
  24408. // Physics
  24409. if (this._physicsEngine) {
  24410. this.onBeforePhysicsObservable.notifyObservers(this);
  24411. this._physicsEngine._step(deltaTime / 1000.0);
  24412. this.onAfterPhysicsObservable.notifyObservers(this);
  24413. }
  24414. }
  24415. // update gamepad manager
  24416. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24417. this._gamepadManager._checkGamepadsStatus();
  24418. }
  24419. // Update Cameras
  24420. if (this.activeCameras.length > 0) {
  24421. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24422. var camera = this.activeCameras[cameraIndex];
  24423. camera.update();
  24424. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24425. // rig cameras
  24426. for (var index = 0; index < camera._rigCameras.length; index++) {
  24427. camera._rigCameras[index].update();
  24428. }
  24429. }
  24430. }
  24431. }
  24432. else if (this.activeCamera) {
  24433. this.activeCamera.update();
  24434. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24435. // rig cameras
  24436. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24437. this.activeCamera._rigCameras[index].update();
  24438. }
  24439. }
  24440. }
  24441. // Before render
  24442. this.onBeforeRenderObservable.notifyObservers(this);
  24443. // Customs render targets
  24444. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24445. var engine = this.getEngine();
  24446. var currentActiveCamera = this.activeCamera;
  24447. if (this.renderTargetsEnabled) {
  24448. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24449. this._intermediateRendering = true;
  24450. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24451. var renderTarget = this.customRenderTargets[customIndex];
  24452. if (renderTarget._shouldRender()) {
  24453. this._renderId++;
  24454. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24455. if (!this.activeCamera)
  24456. throw new Error("Active camera not set");
  24457. // Viewport
  24458. engine.setViewport(this.activeCamera.viewport);
  24459. // Camera
  24460. this.updateTransformMatrix();
  24461. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24462. }
  24463. }
  24464. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24465. this._intermediateRendering = false;
  24466. this._renderId++;
  24467. }
  24468. // Restore back buffer
  24469. if (this.customRenderTargets.length > 0) {
  24470. engine.restoreDefaultFramebuffer();
  24471. }
  24472. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24473. this.activeCamera = currentActiveCamera;
  24474. // Procedural textures
  24475. if (this.proceduralTexturesEnabled) {
  24476. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24477. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24478. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24479. if (proceduralTexture._shouldRender()) {
  24480. proceduralTexture.render();
  24481. }
  24482. }
  24483. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24484. }
  24485. // Clear
  24486. if (this.autoClearDepthAndStencil || this.autoClear) {
  24487. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24488. }
  24489. // Shadows
  24490. if (this.shadowsEnabled) {
  24491. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24492. var light = this.lights[lightIndex];
  24493. var shadowGenerator = light.getShadowGenerator();
  24494. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24495. var shadowMap = (shadowGenerator.getShadowMap());
  24496. if (this.textures.indexOf(shadowMap) !== -1) {
  24497. this._renderTargets.push(shadowMap);
  24498. }
  24499. }
  24500. }
  24501. }
  24502. // Depth renderer
  24503. for (var key in this._depthRenderer) {
  24504. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24505. }
  24506. // Geometry renderer
  24507. if (this._geometryBufferRenderer) {
  24508. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24509. }
  24510. // RenderPipeline
  24511. if (this._postProcessRenderPipelineManager) {
  24512. this._postProcessRenderPipelineManager.update();
  24513. }
  24514. // Multi-cameras?
  24515. if (this.activeCameras.length > 0) {
  24516. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24517. if (cameraIndex > 0) {
  24518. this._engine.clear(null, false, true, true);
  24519. }
  24520. this._processSubCameras(this.activeCameras[cameraIndex]);
  24521. }
  24522. }
  24523. else {
  24524. if (!this.activeCamera) {
  24525. throw new Error("No camera defined");
  24526. }
  24527. this._processSubCameras(this.activeCamera);
  24528. }
  24529. // Intersection checks
  24530. this._checkIntersections();
  24531. // Update the audio listener attached to the camera
  24532. if (BABYLON.AudioEngine) {
  24533. this._updateAudioParameters();
  24534. }
  24535. // After render
  24536. if (this.afterRender) {
  24537. this.afterRender();
  24538. }
  24539. this.onAfterRenderObservable.notifyObservers(this);
  24540. // Cleaning
  24541. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24542. var data = this._toBeDisposed.data[index];
  24543. if (data) {
  24544. data.dispose();
  24545. }
  24546. this._toBeDisposed[index] = null;
  24547. }
  24548. this._toBeDisposed.reset();
  24549. if (this.dumpNextRenderTargets) {
  24550. this.dumpNextRenderTargets = false;
  24551. }
  24552. this._activeBones.addCount(0, true);
  24553. this._activeIndices.addCount(0, true);
  24554. this._activeParticles.addCount(0, true);
  24555. };
  24556. Scene.prototype._updateAudioParameters = function () {
  24557. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24558. return;
  24559. }
  24560. var listeningCamera;
  24561. var audioEngine = BABYLON.Engine.audioEngine;
  24562. if (this.activeCameras.length > 0) {
  24563. listeningCamera = this.activeCameras[0];
  24564. }
  24565. else {
  24566. listeningCamera = this.activeCamera;
  24567. }
  24568. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24569. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24570. // for VR cameras
  24571. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24572. listeningCamera = listeningCamera.rigCameras[0];
  24573. }
  24574. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24575. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24576. cameraDirection.normalize();
  24577. // To avoid some errors on GearVR
  24578. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24579. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24580. }
  24581. var i;
  24582. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24583. var sound = this.mainSoundTrack.soundCollection[i];
  24584. if (sound.useCustomAttenuation) {
  24585. sound.updateDistanceFromListener();
  24586. }
  24587. }
  24588. for (i = 0; i < this.soundTracks.length; i++) {
  24589. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24590. sound = this.soundTracks[i].soundCollection[j];
  24591. if (sound.useCustomAttenuation) {
  24592. sound.updateDistanceFromListener();
  24593. }
  24594. }
  24595. }
  24596. }
  24597. };
  24598. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24599. // Audio
  24600. get: function () {
  24601. return this._audioEnabled;
  24602. },
  24603. set: function (value) {
  24604. this._audioEnabled = value;
  24605. if (BABYLON.AudioEngine) {
  24606. if (this._audioEnabled) {
  24607. this._enableAudio();
  24608. }
  24609. else {
  24610. this._disableAudio();
  24611. }
  24612. }
  24613. },
  24614. enumerable: true,
  24615. configurable: true
  24616. });
  24617. Scene.prototype._disableAudio = function () {
  24618. var i;
  24619. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24620. this.mainSoundTrack.soundCollection[i].pause();
  24621. }
  24622. for (i = 0; i < this.soundTracks.length; i++) {
  24623. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24624. this.soundTracks[i].soundCollection[j].pause();
  24625. }
  24626. }
  24627. };
  24628. Scene.prototype._enableAudio = function () {
  24629. var i;
  24630. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24631. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24632. this.mainSoundTrack.soundCollection[i].play();
  24633. }
  24634. }
  24635. for (i = 0; i < this.soundTracks.length; i++) {
  24636. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24637. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24638. this.soundTracks[i].soundCollection[j].play();
  24639. }
  24640. }
  24641. }
  24642. };
  24643. Object.defineProperty(Scene.prototype, "headphone", {
  24644. get: function () {
  24645. return this._headphone;
  24646. },
  24647. set: function (value) {
  24648. this._headphone = value;
  24649. if (BABYLON.AudioEngine) {
  24650. if (this._headphone) {
  24651. this._switchAudioModeForHeadphones();
  24652. }
  24653. else {
  24654. this._switchAudioModeForNormalSpeakers();
  24655. }
  24656. }
  24657. },
  24658. enumerable: true,
  24659. configurable: true
  24660. });
  24661. Scene.prototype._switchAudioModeForHeadphones = function () {
  24662. this.mainSoundTrack.switchPanningModelToHRTF();
  24663. for (var i = 0; i < this.soundTracks.length; i++) {
  24664. this.soundTracks[i].switchPanningModelToHRTF();
  24665. }
  24666. };
  24667. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24668. this.mainSoundTrack.switchPanningModelToEqualPower();
  24669. for (var i = 0; i < this.soundTracks.length; i++) {
  24670. this.soundTracks[i].switchPanningModelToEqualPower();
  24671. }
  24672. };
  24673. /**
  24674. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24675. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24676. * @returns the created depth renderer
  24677. */
  24678. Scene.prototype.enableDepthRenderer = function (camera) {
  24679. camera = camera || this.activeCamera;
  24680. if (!camera) {
  24681. throw "No camera available to enable depth renderer";
  24682. }
  24683. if (!this._depthRenderer[camera.id]) {
  24684. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24685. }
  24686. return this._depthRenderer[camera.id];
  24687. };
  24688. /**
  24689. * Disables a depth renderer for a given camera
  24690. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24691. */
  24692. Scene.prototype.disableDepthRenderer = function (camera) {
  24693. camera = camera || this.activeCamera;
  24694. if (!camera || !this._depthRenderer[camera.id]) {
  24695. return;
  24696. }
  24697. this._depthRenderer[camera.id].dispose();
  24698. delete this._depthRenderer[camera.id];
  24699. };
  24700. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24701. if (ratio === void 0) { ratio = 1; }
  24702. if (this._geometryBufferRenderer) {
  24703. return this._geometryBufferRenderer;
  24704. }
  24705. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24706. if (!this._geometryBufferRenderer.isSupported) {
  24707. this._geometryBufferRenderer = null;
  24708. }
  24709. return this._geometryBufferRenderer;
  24710. };
  24711. Scene.prototype.disableGeometryBufferRenderer = function () {
  24712. if (!this._geometryBufferRenderer) {
  24713. return;
  24714. }
  24715. this._geometryBufferRenderer.dispose();
  24716. this._geometryBufferRenderer = null;
  24717. };
  24718. Scene.prototype.freezeMaterials = function () {
  24719. for (var i = 0; i < this.materials.length; i++) {
  24720. this.materials[i].freeze();
  24721. }
  24722. };
  24723. Scene.prototype.unfreezeMaterials = function () {
  24724. for (var i = 0; i < this.materials.length; i++) {
  24725. this.materials[i].unfreeze();
  24726. }
  24727. };
  24728. Scene.prototype.dispose = function () {
  24729. this.beforeRender = null;
  24730. this.afterRender = null;
  24731. this.skeletons = [];
  24732. this.morphTargetManagers = [];
  24733. this.importedMeshesFiles = new Array();
  24734. this.stopAllAnimations();
  24735. this.resetCachedMaterial();
  24736. for (var key in this._depthRenderer) {
  24737. this._depthRenderer[key].dispose();
  24738. }
  24739. if (this._gamepadManager) {
  24740. this._gamepadManager.dispose();
  24741. this._gamepadManager = null;
  24742. }
  24743. // Smart arrays
  24744. if (this.activeCamera) {
  24745. this.activeCamera._activeMeshes.dispose();
  24746. this.activeCamera = null;
  24747. }
  24748. this._activeMeshes.dispose();
  24749. this._renderingManager.dispose();
  24750. this._processedMaterials.dispose();
  24751. this._activeParticleSystems.dispose();
  24752. this._activeSkeletons.dispose();
  24753. this._softwareSkinnedMeshes.dispose();
  24754. this._renderTargets.dispose();
  24755. if (this._boundingBoxRenderer) {
  24756. this._boundingBoxRenderer.dispose();
  24757. }
  24758. this._meshesForIntersections.dispose();
  24759. this._toBeDisposed.dispose();
  24760. // Abort active requests
  24761. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24762. var request = _a[_i];
  24763. request.abort();
  24764. }
  24765. // Debug layer
  24766. if (this._debugLayer) {
  24767. this._debugLayer.hide();
  24768. }
  24769. // Events
  24770. this.onDisposeObservable.notifyObservers(this);
  24771. this.onDisposeObservable.clear();
  24772. this.onBeforeRenderObservable.clear();
  24773. this.onAfterRenderObservable.clear();
  24774. this.OnBeforeRenderTargetsRenderObservable.clear();
  24775. this.OnAfterRenderTargetsRenderObservable.clear();
  24776. this.onAfterStepObservable.clear();
  24777. this.onBeforeStepObservable.clear();
  24778. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24779. this.onAfterActiveMeshesEvaluationObservable.clear();
  24780. this.onBeforeParticlesRenderingObservable.clear();
  24781. this.onAfterParticlesRenderingObservable.clear();
  24782. this.onBeforeSpritesRenderingObservable.clear();
  24783. this.onAfterSpritesRenderingObservable.clear();
  24784. this.onBeforeDrawPhaseObservable.clear();
  24785. this.onAfterDrawPhaseObservable.clear();
  24786. this.onBeforePhysicsObservable.clear();
  24787. this.onAfterPhysicsObservable.clear();
  24788. this.onBeforeAnimationsObservable.clear();
  24789. this.onAfterAnimationsObservable.clear();
  24790. this.onDataLoadedObservable.clear();
  24791. this.detachControl();
  24792. // Release sounds & sounds tracks
  24793. if (BABYLON.AudioEngine) {
  24794. this.disposeSounds();
  24795. }
  24796. // VR Helper
  24797. if (this.VRHelper) {
  24798. this.VRHelper.dispose();
  24799. }
  24800. // Detach cameras
  24801. var canvas = this._engine.getRenderingCanvas();
  24802. if (canvas) {
  24803. var index;
  24804. for (index = 0; index < this.cameras.length; index++) {
  24805. this.cameras[index].detachControl(canvas);
  24806. }
  24807. }
  24808. // Release animation groups
  24809. while (this.animationGroups.length) {
  24810. this.animationGroups[0].dispose();
  24811. }
  24812. // Release lights
  24813. while (this.lights.length) {
  24814. this.lights[0].dispose();
  24815. }
  24816. // Release meshes
  24817. while (this.meshes.length) {
  24818. this.meshes[0].dispose(true);
  24819. }
  24820. while (this.transformNodes.length) {
  24821. this.removeTransformNode(this.transformNodes[0]);
  24822. }
  24823. // Release cameras
  24824. while (this.cameras.length) {
  24825. this.cameras[0].dispose();
  24826. }
  24827. // Release materials
  24828. if (this.defaultMaterial) {
  24829. this.defaultMaterial.dispose();
  24830. }
  24831. while (this.multiMaterials.length) {
  24832. this.multiMaterials[0].dispose();
  24833. }
  24834. while (this.materials.length) {
  24835. this.materials[0].dispose();
  24836. }
  24837. // Release particles
  24838. while (this.particleSystems.length) {
  24839. this.particleSystems[0].dispose();
  24840. }
  24841. // Release sprites
  24842. while (this.spriteManagers.length) {
  24843. this.spriteManagers[0].dispose();
  24844. }
  24845. // Release postProcesses
  24846. while (this.postProcesses.length) {
  24847. this.postProcesses[0].dispose();
  24848. }
  24849. // Release layers
  24850. while (this.layers.length) {
  24851. this.layers[0].dispose();
  24852. }
  24853. while (this.effectLayers.length) {
  24854. this.effectLayers[0].dispose();
  24855. }
  24856. // Release textures
  24857. while (this.textures.length) {
  24858. this.textures[0].dispose();
  24859. }
  24860. // Release UBO
  24861. this._sceneUbo.dispose();
  24862. if (this._alternateSceneUbo) {
  24863. this._alternateSceneUbo.dispose();
  24864. }
  24865. // Post-processes
  24866. this.postProcessManager.dispose();
  24867. if (this._postProcessRenderPipelineManager) {
  24868. this._postProcessRenderPipelineManager.dispose();
  24869. }
  24870. // Physics
  24871. if (this._physicsEngine) {
  24872. this.disablePhysicsEngine();
  24873. }
  24874. // Remove from engine
  24875. index = this._engine.scenes.indexOf(this);
  24876. if (index > -1) {
  24877. this._engine.scenes.splice(index, 1);
  24878. }
  24879. this._engine.wipeCaches(true);
  24880. this._isDisposed = true;
  24881. };
  24882. Object.defineProperty(Scene.prototype, "isDisposed", {
  24883. get: function () {
  24884. return this._isDisposed;
  24885. },
  24886. enumerable: true,
  24887. configurable: true
  24888. });
  24889. // Release sounds & sounds tracks
  24890. Scene.prototype.disposeSounds = function () {
  24891. if (!this._mainSoundTrack) {
  24892. return;
  24893. }
  24894. this.mainSoundTrack.dispose();
  24895. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24896. this.soundTracks[scIndex].dispose();
  24897. }
  24898. };
  24899. // Octrees
  24900. /**
  24901. * Get the world extend vectors with an optional filter
  24902. *
  24903. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24904. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24905. */
  24906. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24907. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24908. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24909. filterPredicate = filterPredicate || (function () { return true; });
  24910. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24911. mesh.computeWorldMatrix(true);
  24912. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24913. return;
  24914. }
  24915. var boundingInfo = mesh.getBoundingInfo();
  24916. var minBox = boundingInfo.boundingBox.minimumWorld;
  24917. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24918. BABYLON.Tools.CheckExtends(minBox, min, max);
  24919. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24920. });
  24921. return {
  24922. min: min,
  24923. max: max
  24924. };
  24925. };
  24926. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24927. if (maxCapacity === void 0) { maxCapacity = 64; }
  24928. if (maxDepth === void 0) { maxDepth = 2; }
  24929. if (!this._selectionOctree) {
  24930. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24931. }
  24932. var worldExtends = this.getWorldExtends();
  24933. // Update octree
  24934. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24935. return this._selectionOctree;
  24936. };
  24937. // Picking
  24938. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24939. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24940. var result = BABYLON.Ray.Zero();
  24941. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24942. return result;
  24943. };
  24944. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24945. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24946. var engine = this._engine;
  24947. if (!camera) {
  24948. if (!this.activeCamera)
  24949. throw new Error("Active camera not set");
  24950. camera = this.activeCamera;
  24951. }
  24952. var cameraViewport = camera.viewport;
  24953. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24954. // Moving coordinates to local viewport world
  24955. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24956. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24957. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24958. return this;
  24959. };
  24960. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24961. var result = BABYLON.Ray.Zero();
  24962. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24963. return result;
  24964. };
  24965. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24966. if (!BABYLON.PickingInfo) {
  24967. return this;
  24968. }
  24969. var engine = this._engine;
  24970. if (!camera) {
  24971. if (!this.activeCamera)
  24972. throw new Error("Active camera not set");
  24973. camera = this.activeCamera;
  24974. }
  24975. var cameraViewport = camera.viewport;
  24976. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24977. var identity = BABYLON.Matrix.Identity();
  24978. // Moving coordinates to local viewport world
  24979. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24980. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24981. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24982. return this;
  24983. };
  24984. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24985. if (!BABYLON.PickingInfo) {
  24986. return null;
  24987. }
  24988. var pickingInfo = null;
  24989. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24990. var mesh = this.meshes[meshIndex];
  24991. if (predicate) {
  24992. if (!predicate(mesh)) {
  24993. continue;
  24994. }
  24995. }
  24996. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24997. continue;
  24998. }
  24999. var world = mesh.getWorldMatrix();
  25000. var ray = rayFunction(world);
  25001. var result = mesh.intersects(ray, fastCheck);
  25002. if (!result || !result.hit)
  25003. continue;
  25004. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25005. continue;
  25006. pickingInfo = result;
  25007. if (fastCheck) {
  25008. break;
  25009. }
  25010. }
  25011. return pickingInfo || new BABYLON.PickingInfo();
  25012. };
  25013. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25014. if (!BABYLON.PickingInfo) {
  25015. return null;
  25016. }
  25017. var pickingInfos = new Array();
  25018. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25019. var mesh = this.meshes[meshIndex];
  25020. if (predicate) {
  25021. if (!predicate(mesh)) {
  25022. continue;
  25023. }
  25024. }
  25025. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25026. continue;
  25027. }
  25028. var world = mesh.getWorldMatrix();
  25029. var ray = rayFunction(world);
  25030. var result = mesh.intersects(ray, false);
  25031. if (!result || !result.hit)
  25032. continue;
  25033. pickingInfos.push(result);
  25034. }
  25035. return pickingInfos;
  25036. };
  25037. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25038. if (!BABYLON.PickingInfo) {
  25039. return null;
  25040. }
  25041. var pickingInfo = null;
  25042. if (!camera) {
  25043. if (!this.activeCamera) {
  25044. return null;
  25045. }
  25046. camera = this.activeCamera;
  25047. }
  25048. if (this.spriteManagers.length > 0) {
  25049. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25050. var spriteManager = this.spriteManagers[spriteIndex];
  25051. if (!spriteManager.isPickable) {
  25052. continue;
  25053. }
  25054. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25055. if (!result || !result.hit)
  25056. continue;
  25057. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25058. continue;
  25059. pickingInfo = result;
  25060. if (fastCheck) {
  25061. break;
  25062. }
  25063. }
  25064. }
  25065. return pickingInfo || new BABYLON.PickingInfo();
  25066. };
  25067. /** Launch a ray to try to pick a mesh in the scene
  25068. * @param x position on screen
  25069. * @param y position on screen
  25070. * @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
  25071. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25072. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25073. */
  25074. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25075. var _this = this;
  25076. if (!BABYLON.PickingInfo) {
  25077. return null;
  25078. }
  25079. return this._internalPick(function (world) {
  25080. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25081. return _this._tempPickingRay;
  25082. }, predicate, fastCheck);
  25083. };
  25084. /** Launch a ray to try to pick a sprite in the scene
  25085. * @param x position on screen
  25086. * @param y position on screen
  25087. * @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
  25088. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25089. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25090. */
  25091. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25092. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25093. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25094. };
  25095. /** Use the given ray to pick a mesh in the scene
  25096. * @param ray The ray to use to pick meshes
  25097. * @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
  25098. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25099. */
  25100. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25101. var _this = this;
  25102. return this._internalPick(function (world) {
  25103. if (!_this._pickWithRayInverseMatrix) {
  25104. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25105. }
  25106. world.invertToRef(_this._pickWithRayInverseMatrix);
  25107. if (!_this._cachedRayForTransform) {
  25108. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25109. }
  25110. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25111. return _this._cachedRayForTransform;
  25112. }, predicate, fastCheck);
  25113. };
  25114. /**
  25115. * Launch a ray to try to pick a mesh in the scene
  25116. * @param x X position on screen
  25117. * @param y Y position on screen
  25118. * @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
  25119. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25120. */
  25121. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25122. var _this = this;
  25123. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25124. };
  25125. /**
  25126. * Launch a ray to try to pick a mesh in the scene
  25127. * @param ray Ray to use
  25128. * @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
  25129. */
  25130. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25131. var _this = this;
  25132. return this._internalMultiPick(function (world) {
  25133. if (!_this._pickWithRayInverseMatrix) {
  25134. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25135. }
  25136. world.invertToRef(_this._pickWithRayInverseMatrix);
  25137. if (!_this._cachedRayForTransform) {
  25138. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25139. }
  25140. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25141. return _this._cachedRayForTransform;
  25142. }, predicate);
  25143. };
  25144. Scene.prototype.setPointerOverMesh = function (mesh) {
  25145. if (this._pointerOverMesh === mesh) {
  25146. return;
  25147. }
  25148. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25149. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25150. }
  25151. this._pointerOverMesh = mesh;
  25152. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25153. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25154. }
  25155. };
  25156. Scene.prototype.getPointerOverMesh = function () {
  25157. return this._pointerOverMesh;
  25158. };
  25159. Scene.prototype.setPointerOverSprite = function (sprite) {
  25160. if (this._pointerOverSprite === sprite) {
  25161. return;
  25162. }
  25163. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25164. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25165. }
  25166. this._pointerOverSprite = sprite;
  25167. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25168. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25169. }
  25170. };
  25171. Scene.prototype.getPointerOverSprite = function () {
  25172. return this._pointerOverSprite;
  25173. };
  25174. // Physics
  25175. Scene.prototype.getPhysicsEngine = function () {
  25176. return this._physicsEngine;
  25177. };
  25178. /**
  25179. * Enables physics to the current scene
  25180. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25181. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25182. * @return {boolean} was the physics engine initialized
  25183. */
  25184. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25185. if (gravity === void 0) { gravity = null; }
  25186. if (this._physicsEngine) {
  25187. return true;
  25188. }
  25189. try {
  25190. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25191. return true;
  25192. }
  25193. catch (e) {
  25194. BABYLON.Tools.Error(e.message);
  25195. return false;
  25196. }
  25197. };
  25198. Scene.prototype.disablePhysicsEngine = function () {
  25199. if (!this._physicsEngine) {
  25200. return;
  25201. }
  25202. this._physicsEngine.dispose();
  25203. this._physicsEngine = null;
  25204. };
  25205. Scene.prototype.isPhysicsEnabled = function () {
  25206. return this._physicsEngine !== undefined;
  25207. };
  25208. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25209. var mesh = compound.parts[0].mesh;
  25210. if (mesh.physicsImpostor) {
  25211. mesh.physicsImpostor.dispose();
  25212. mesh.physicsImpostor = null;
  25213. }
  25214. };
  25215. // Misc.
  25216. Scene.prototype._rebuildGeometries = function () {
  25217. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25218. var geometry = _a[_i];
  25219. geometry._rebuild();
  25220. }
  25221. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25222. var mesh = _c[_b];
  25223. mesh._rebuild();
  25224. }
  25225. if (this.postProcessManager) {
  25226. this.postProcessManager._rebuild();
  25227. }
  25228. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25229. var layer = _e[_d];
  25230. layer._rebuild();
  25231. }
  25232. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25233. var effectLayer = _g[_f];
  25234. effectLayer._rebuild();
  25235. }
  25236. if (this._boundingBoxRenderer) {
  25237. this._boundingBoxRenderer._rebuild();
  25238. }
  25239. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25240. var system = _j[_h];
  25241. system.rebuild();
  25242. }
  25243. if (this._postProcessRenderPipelineManager) {
  25244. this._postProcessRenderPipelineManager._rebuild();
  25245. }
  25246. };
  25247. Scene.prototype._rebuildTextures = function () {
  25248. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25249. var texture = _a[_i];
  25250. texture._rebuild();
  25251. }
  25252. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25253. };
  25254. /**
  25255. * Creates a default light for the scene.
  25256. * @param replace Whether to replace the existing lights in the scene.
  25257. */
  25258. Scene.prototype.createDefaultLight = function (replace) {
  25259. if (replace === void 0) { replace = false; }
  25260. // Dispose existing light in replace mode.
  25261. if (replace) {
  25262. if (this.lights) {
  25263. for (var i = 0; i < this.lights.length; i++) {
  25264. this.lights[i].dispose();
  25265. }
  25266. }
  25267. }
  25268. // Light
  25269. if (this.lights.length === 0) {
  25270. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25271. }
  25272. };
  25273. /**
  25274. * Creates a default camera for the scene.
  25275. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25276. * @param replace Whether to replace the existing active camera in the scene.
  25277. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25278. */
  25279. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25280. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25281. if (replace === void 0) { replace = false; }
  25282. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25283. // Dispose existing camera in replace mode.
  25284. if (replace) {
  25285. if (this.activeCamera) {
  25286. this.activeCamera.dispose();
  25287. this.activeCamera = null;
  25288. }
  25289. }
  25290. // Camera
  25291. if (!this.activeCamera) {
  25292. var worldExtends = this.getWorldExtends();
  25293. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25294. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25295. var camera;
  25296. var radius = worldSize.length() * 1.5;
  25297. // empty scene scenario!
  25298. if (!isFinite(radius)) {
  25299. radius = 1;
  25300. worldCenter.copyFromFloats(0, 0, 0);
  25301. }
  25302. if (createArcRotateCamera) {
  25303. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25304. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25305. arcRotateCamera.wheelPrecision = 100 / radius;
  25306. camera = arcRotateCamera;
  25307. }
  25308. else {
  25309. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25310. freeCamera.setTarget(worldCenter);
  25311. camera = freeCamera;
  25312. }
  25313. camera.minZ = radius * 0.01;
  25314. camera.maxZ = radius * 1000;
  25315. camera.speed = radius * 0.2;
  25316. this.activeCamera = camera;
  25317. var canvas = this.getEngine().getRenderingCanvas();
  25318. if (attachCameraControls && canvas) {
  25319. camera.attachControl(canvas);
  25320. }
  25321. }
  25322. };
  25323. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25324. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25325. if (replace === void 0) { replace = false; }
  25326. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25327. this.createDefaultLight(replace);
  25328. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25329. };
  25330. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25331. if (pbr === void 0) { pbr = false; }
  25332. if (scale === void 0) { scale = 1000; }
  25333. if (blur === void 0) { blur = 0; }
  25334. if (environmentTexture) {
  25335. this.environmentTexture = environmentTexture;
  25336. }
  25337. if (!this.environmentTexture) {
  25338. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25339. return null;
  25340. }
  25341. // Skybox
  25342. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25343. if (pbr) {
  25344. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25345. hdrSkyboxMaterial.backFaceCulling = false;
  25346. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25347. if (hdrSkyboxMaterial.reflectionTexture) {
  25348. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25349. }
  25350. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25351. hdrSkyboxMaterial.disableLighting = true;
  25352. hdrSkyboxMaterial.twoSidedLighting = true;
  25353. hdrSkybox.infiniteDistance = true;
  25354. hdrSkybox.material = hdrSkyboxMaterial;
  25355. }
  25356. else {
  25357. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25358. skyboxMaterial.backFaceCulling = false;
  25359. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25360. if (skyboxMaterial.reflectionTexture) {
  25361. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25362. }
  25363. skyboxMaterial.disableLighting = true;
  25364. hdrSkybox.infiniteDistance = true;
  25365. hdrSkybox.material = skyboxMaterial;
  25366. }
  25367. return hdrSkybox;
  25368. };
  25369. Scene.prototype.createDefaultEnvironment = function (options) {
  25370. if (BABYLON.EnvironmentHelper) {
  25371. return new BABYLON.EnvironmentHelper(options, this);
  25372. }
  25373. return null;
  25374. };
  25375. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25376. if (webVROptions === void 0) { webVROptions = {}; }
  25377. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25378. };
  25379. // Tags
  25380. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25381. if (tagsQuery === undefined) {
  25382. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25383. return list;
  25384. }
  25385. var listByTags = [];
  25386. forEach = forEach || (function (item) { return; });
  25387. for (var i in list) {
  25388. var item = list[i];
  25389. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25390. listByTags.push(item);
  25391. forEach(item);
  25392. }
  25393. }
  25394. return listByTags;
  25395. };
  25396. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25397. return this._getByTags(this.meshes, tagsQuery, forEach);
  25398. };
  25399. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25400. return this._getByTags(this.cameras, tagsQuery, forEach);
  25401. };
  25402. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25403. return this._getByTags(this.lights, tagsQuery, forEach);
  25404. };
  25405. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25406. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25407. };
  25408. /**
  25409. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25410. * This allowed control for front to back rendering or reversly depending of the special needs.
  25411. *
  25412. * @param renderingGroupId The rendering group id corresponding to its index
  25413. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25414. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25415. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25416. */
  25417. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25418. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25419. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25420. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25421. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25422. };
  25423. /**
  25424. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25425. *
  25426. * @param renderingGroupId The rendering group id corresponding to its index
  25427. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25428. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25429. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25430. */
  25431. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25432. if (depth === void 0) { depth = true; }
  25433. if (stencil === void 0) { stencil = true; }
  25434. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25435. };
  25436. /**
  25437. * Will flag all materials as dirty to trigger new shader compilation
  25438. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25439. */
  25440. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25441. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25442. var material = _a[_i];
  25443. if (predicate && !predicate(material)) {
  25444. continue;
  25445. }
  25446. material.markAsDirty(flag);
  25447. }
  25448. };
  25449. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25450. var _this = this;
  25451. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25452. this._activeRequests.push(request);
  25453. request.onCompleteObservable.add(function (request) {
  25454. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25455. });
  25456. return request;
  25457. };
  25458. /** @ignore */
  25459. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25460. var _this = this;
  25461. return new Promise(function (resolve, reject) {
  25462. _this._loadFile(url, function (data) {
  25463. resolve(data);
  25464. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25465. reject(exception);
  25466. });
  25467. });
  25468. };
  25469. // Statics
  25470. Scene._FOGMODE_NONE = 0;
  25471. Scene._FOGMODE_EXP = 1;
  25472. Scene._FOGMODE_EXP2 = 2;
  25473. Scene._FOGMODE_LINEAR = 3;
  25474. Scene._uniqueIdCounter = 0;
  25475. Scene.MinDeltaTime = 1.0;
  25476. Scene.MaxDeltaTime = 1000.0;
  25477. /** The distance in pixel that you have to move to prevent some events */
  25478. Scene.DragMovementThreshold = 10; // in pixels
  25479. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25480. Scene.LongPressDelay = 500; // in milliseconds
  25481. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25482. Scene.DoubleClickDelay = 300; // in milliseconds
  25483. /** If you need to check double click without raising a single click at first click, enable this flag */
  25484. Scene.ExclusiveDoubleClickMode = false;
  25485. return Scene;
  25486. }());
  25487. BABYLON.Scene = Scene;
  25488. })(BABYLON || (BABYLON = {}));
  25489. //# sourceMappingURL=babylon.scene.js.map
  25490. var BABYLON;
  25491. (function (BABYLON) {
  25492. /**
  25493. * Set of assets to keep when moving a scene into an asset container.
  25494. */
  25495. var KeepAssets = /** @class */ (function () {
  25496. function KeepAssets() {
  25497. /**
  25498. * Cameras to keep.
  25499. */
  25500. this.cameras = new Array();
  25501. /**
  25502. * Lights to keep.
  25503. */
  25504. this.lights = new Array();
  25505. /**
  25506. * Meshes to keep.
  25507. */
  25508. this.meshes = new Array();
  25509. /**
  25510. * Skeletons to keep.
  25511. */
  25512. this.skeletons = new Array();
  25513. /**
  25514. * ParticleSystems to keep.
  25515. */
  25516. this.particleSystems = new Array();
  25517. /**
  25518. * Animations to keep.
  25519. */
  25520. this.animations = new Array();
  25521. /**
  25522. * MultiMaterials to keep.
  25523. */
  25524. this.multiMaterials = new Array();
  25525. /**
  25526. * Materials to keep.
  25527. */
  25528. this.materials = new Array();
  25529. /**
  25530. * MorphTargetManagers to keep.
  25531. */
  25532. this.morphTargetManagers = new Array();
  25533. /**
  25534. * Geometries to keep.
  25535. */
  25536. this.geometries = new Array();
  25537. /**
  25538. * TransformNodes to keep.
  25539. */
  25540. this.transformNodes = new Array();
  25541. /**
  25542. * LensFlareSystems to keep.
  25543. */
  25544. this.lensFlareSystems = new Array();
  25545. /**
  25546. * ShadowGenerators to keep.
  25547. */
  25548. this.shadowGenerators = new Array();
  25549. /**
  25550. * ActionManagers to keep.
  25551. */
  25552. this.actionManagers = new Array();
  25553. /**
  25554. * Sounds to keep.
  25555. */
  25556. this.sounds = new Array();
  25557. }
  25558. return KeepAssets;
  25559. }());
  25560. BABYLON.KeepAssets = KeepAssets;
  25561. /**
  25562. * Container with a set of assets that can be added or removed from a scene.
  25563. */
  25564. var AssetContainer = /** @class */ (function () {
  25565. /**
  25566. * Instantiates an AssetContainer.
  25567. * @param scene The scene the AssetContainer belongs to.
  25568. */
  25569. function AssetContainer(scene) {
  25570. // Objects
  25571. /**
  25572. * Cameras populated in the container.
  25573. */
  25574. this.cameras = new Array();
  25575. /**
  25576. * Lights populated in the container.
  25577. */
  25578. this.lights = new Array();
  25579. /**
  25580. * Meshes populated in the container.
  25581. */
  25582. this.meshes = new Array();
  25583. /**
  25584. * Skeletons populated in the container.
  25585. */
  25586. this.skeletons = new Array();
  25587. /**
  25588. * ParticleSystems populated in the container.
  25589. */
  25590. this.particleSystems = new Array();
  25591. /**
  25592. * Animations populated in the container.
  25593. */
  25594. this.animations = new Array();
  25595. /**
  25596. * MultiMaterials populated in the container.
  25597. */
  25598. this.multiMaterials = new Array();
  25599. /**
  25600. * Materials populated in the container.
  25601. */
  25602. this.materials = new Array();
  25603. /**
  25604. * MorphTargetManagers populated in the container.
  25605. */
  25606. this.morphTargetManagers = new Array();
  25607. /**
  25608. * Geometries populated in the container.
  25609. */
  25610. this.geometries = new Array();
  25611. /**
  25612. * TransformNodes populated in the container.
  25613. */
  25614. this.transformNodes = new Array();
  25615. /**
  25616. * LensFlareSystems populated in the container.
  25617. */
  25618. this.lensFlareSystems = new Array();
  25619. /**
  25620. * ShadowGenerators populated in the container.
  25621. */
  25622. this.shadowGenerators = new Array();
  25623. /**
  25624. * ActionManagers populated in the container.
  25625. */
  25626. this.actionManagers = new Array();
  25627. /**
  25628. * Sounds populated in the container.
  25629. */
  25630. this.sounds = new Array();
  25631. this.scene = scene;
  25632. }
  25633. /**
  25634. * Adds all the assets from the container to the scene.
  25635. */
  25636. AssetContainer.prototype.addAllToScene = function () {
  25637. var _this = this;
  25638. this.cameras.forEach(function (o) {
  25639. _this.scene.addCamera(o);
  25640. });
  25641. this.lights.forEach(function (o) {
  25642. _this.scene.addLight(o);
  25643. });
  25644. this.meshes.forEach(function (o) {
  25645. _this.scene.addMesh(o);
  25646. });
  25647. this.skeletons.forEach(function (o) {
  25648. _this.scene.addSkeleton(o);
  25649. });
  25650. this.particleSystems.forEach(function (o) {
  25651. _this.scene.addParticleSystem(o);
  25652. });
  25653. this.animations.forEach(function (o) {
  25654. _this.scene.addAnimation(o);
  25655. });
  25656. this.multiMaterials.forEach(function (o) {
  25657. _this.scene.addMultiMaterial(o);
  25658. });
  25659. this.materials.forEach(function (o) {
  25660. _this.scene.addMaterial(o);
  25661. });
  25662. this.morphTargetManagers.forEach(function (o) {
  25663. _this.scene.addMorphTargetManager(o);
  25664. });
  25665. this.geometries.forEach(function (o) {
  25666. _this.scene.addGeometry(o);
  25667. });
  25668. this.transformNodes.forEach(function (o) {
  25669. _this.scene.addTransformNode(o);
  25670. });
  25671. this.lensFlareSystems.forEach(function (o) {
  25672. _this.scene.addLensFlareSystem(o);
  25673. });
  25674. this.actionManagers.forEach(function (o) {
  25675. _this.scene.addActionManager(o);
  25676. });
  25677. this.sounds.forEach(function (o) {
  25678. o.play();
  25679. o.autoplay = true;
  25680. _this.scene.mainSoundTrack.AddSound(o);
  25681. });
  25682. };
  25683. /**
  25684. * Removes all the assets in the container from the scene
  25685. */
  25686. AssetContainer.prototype.removeAllFromScene = function () {
  25687. var _this = this;
  25688. this.cameras.forEach(function (o) {
  25689. _this.scene.removeCamera(o);
  25690. });
  25691. this.lights.forEach(function (o) {
  25692. _this.scene.removeLight(o);
  25693. });
  25694. this.meshes.forEach(function (o) {
  25695. _this.scene.removeMesh(o);
  25696. });
  25697. this.skeletons.forEach(function (o) {
  25698. _this.scene.removeSkeleton(o);
  25699. });
  25700. this.particleSystems.forEach(function (o) {
  25701. _this.scene.removeParticleSystem(o);
  25702. });
  25703. this.animations.forEach(function (o) {
  25704. _this.scene.removeAnimation(o);
  25705. });
  25706. this.multiMaterials.forEach(function (o) {
  25707. _this.scene.removeMultiMaterial(o);
  25708. });
  25709. this.materials.forEach(function (o) {
  25710. _this.scene.removeMaterial(o);
  25711. });
  25712. this.morphTargetManagers.forEach(function (o) {
  25713. _this.scene.removeMorphTargetManager(o);
  25714. });
  25715. this.geometries.forEach(function (o) {
  25716. _this.scene.removeGeometry(o);
  25717. });
  25718. this.transformNodes.forEach(function (o) {
  25719. _this.scene.removeTransformNode(o);
  25720. });
  25721. this.lensFlareSystems.forEach(function (o) {
  25722. _this.scene.removeLensFlareSystem(o);
  25723. });
  25724. this.actionManagers.forEach(function (o) {
  25725. _this.scene.removeActionManager(o);
  25726. });
  25727. this.sounds.forEach(function (o) {
  25728. o.stop();
  25729. o.autoplay = false;
  25730. _this.scene.mainSoundTrack.RemoveSound(o);
  25731. });
  25732. };
  25733. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25734. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25735. var asset = sourceAssets_1[_i];
  25736. var move = true;
  25737. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25738. var keepAsset = keepAssets_1[_a];
  25739. if (asset === keepAsset) {
  25740. move = false;
  25741. break;
  25742. }
  25743. }
  25744. if (move) {
  25745. targetAssets.push(asset);
  25746. }
  25747. }
  25748. };
  25749. /**
  25750. * Removes all the assets contained in the scene and adds them to the container.
  25751. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25752. */
  25753. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25754. if (keepAssets === undefined) {
  25755. keepAssets = new KeepAssets();
  25756. }
  25757. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25758. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25759. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25760. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25761. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25762. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25763. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25764. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25765. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25766. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25767. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25768. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25769. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25770. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25771. this.removeAllFromScene();
  25772. };
  25773. return AssetContainer;
  25774. }());
  25775. BABYLON.AssetContainer = AssetContainer;
  25776. })(BABYLON || (BABYLON = {}));
  25777. //# sourceMappingURL=babylon.assetContainer.js.map
  25778. var BABYLON;
  25779. (function (BABYLON) {
  25780. var Buffer = /** @class */ (function () {
  25781. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25782. if (instanced === void 0) { instanced = false; }
  25783. if (engine instanceof BABYLON.Mesh) {
  25784. this._engine = engine.getScene().getEngine();
  25785. }
  25786. else {
  25787. this._engine = engine;
  25788. }
  25789. this._updatable = updatable;
  25790. this._instanced = instanced;
  25791. this._data = data;
  25792. this._strideSize = stride;
  25793. if (!postponeInternalCreation) {
  25794. this.create();
  25795. }
  25796. }
  25797. /**
  25798. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25799. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25800. * @param offset defines offset in the buffer (0 by default)
  25801. * @param size defines the size in floats of attributes (position is 3 for instance)
  25802. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25803. * @param instanced defines if the vertex buffer contains indexed data
  25804. * @returns the new vertex buffer
  25805. */
  25806. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25807. // a lot of these parameters are ignored as they are overriden by the buffer
  25808. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25809. };
  25810. // Properties
  25811. Buffer.prototype.isUpdatable = function () {
  25812. return this._updatable;
  25813. };
  25814. Buffer.prototype.getData = function () {
  25815. return this._data;
  25816. };
  25817. Buffer.prototype.getBuffer = function () {
  25818. return this._buffer;
  25819. };
  25820. Buffer.prototype.getStrideSize = function () {
  25821. return this._strideSize;
  25822. };
  25823. // public getIsInstanced(): boolean {
  25824. // return this._instanced;
  25825. // }
  25826. // public get instanceDivisor(): number {
  25827. // return this._instanceDivisor;
  25828. // }
  25829. // public set instanceDivisor(value: number) {
  25830. // this._instanceDivisor = value;
  25831. // if (value == 0) {
  25832. // this._instanced = false;
  25833. // } else {
  25834. // this._instanced = true;
  25835. // }
  25836. // }
  25837. // Methods
  25838. Buffer.prototype.create = function (data) {
  25839. if (data === void 0) { data = null; }
  25840. if (!data && this._buffer) {
  25841. return; // nothing to do
  25842. }
  25843. data = data || this._data;
  25844. if (!data) {
  25845. return;
  25846. }
  25847. if (!this._buffer) {
  25848. if (this._updatable) {
  25849. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25850. this._data = data;
  25851. }
  25852. else {
  25853. this._buffer = this._engine.createVertexBuffer(data);
  25854. }
  25855. }
  25856. else if (this._updatable) {
  25857. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25858. this._data = data;
  25859. }
  25860. };
  25861. Buffer.prototype._rebuild = function () {
  25862. this._buffer = null;
  25863. this.create(this._data);
  25864. };
  25865. Buffer.prototype.update = function (data) {
  25866. this.create(data);
  25867. };
  25868. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25869. if (!this._buffer) {
  25870. return;
  25871. }
  25872. if (this._updatable) {
  25873. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25874. this._data = null;
  25875. }
  25876. };
  25877. Buffer.prototype.dispose = function () {
  25878. if (!this._buffer) {
  25879. return;
  25880. }
  25881. if (this._engine._releaseBuffer(this._buffer)) {
  25882. this._buffer = null;
  25883. }
  25884. };
  25885. return Buffer;
  25886. }());
  25887. BABYLON.Buffer = Buffer;
  25888. })(BABYLON || (BABYLON = {}));
  25889. //# sourceMappingURL=babylon.buffer.js.map
  25890. var BABYLON;
  25891. (function (BABYLON) {
  25892. var VertexBuffer = /** @class */ (function () {
  25893. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25894. if (data instanceof BABYLON.Buffer) {
  25895. if (!stride) {
  25896. stride = data.getStrideSize();
  25897. }
  25898. this._buffer = data;
  25899. this._ownsBuffer = false;
  25900. }
  25901. else {
  25902. if (!stride) {
  25903. stride = VertexBuffer.DeduceStride(kind);
  25904. }
  25905. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25906. this._ownsBuffer = true;
  25907. }
  25908. this._stride = stride;
  25909. this._instanced = instanced !== undefined ? instanced : false;
  25910. this._instanceDivisor = instanced ? 1 : 0;
  25911. this._offset = offset ? offset : 0;
  25912. this._size = size ? size : stride;
  25913. this._kind = kind;
  25914. }
  25915. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25916. /**
  25917. * Gets or sets the instance divisor when in instanced mode
  25918. */
  25919. get: function () {
  25920. return this._instanceDivisor;
  25921. },
  25922. set: function (value) {
  25923. this._instanceDivisor = value;
  25924. if (value == 0) {
  25925. this._instanced = false;
  25926. }
  25927. else {
  25928. this._instanced = true;
  25929. }
  25930. },
  25931. enumerable: true,
  25932. configurable: true
  25933. });
  25934. VertexBuffer.prototype._rebuild = function () {
  25935. if (!this._buffer) {
  25936. return;
  25937. }
  25938. this._buffer._rebuild();
  25939. };
  25940. /**
  25941. * Returns the kind of the VertexBuffer (string).
  25942. */
  25943. VertexBuffer.prototype.getKind = function () {
  25944. return this._kind;
  25945. };
  25946. // Properties
  25947. /**
  25948. * Boolean : is the VertexBuffer updatable ?
  25949. */
  25950. VertexBuffer.prototype.isUpdatable = function () {
  25951. return this._buffer.isUpdatable();
  25952. };
  25953. /**
  25954. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25955. */
  25956. VertexBuffer.prototype.getData = function () {
  25957. return this._buffer.getData();
  25958. };
  25959. /**
  25960. * Returns the WebGLBuffer associated to the VertexBuffer.
  25961. */
  25962. VertexBuffer.prototype.getBuffer = function () {
  25963. return this._buffer.getBuffer();
  25964. };
  25965. /**
  25966. * Returns the stride of the VertexBuffer (integer).
  25967. */
  25968. VertexBuffer.prototype.getStrideSize = function () {
  25969. return this._stride;
  25970. };
  25971. /**
  25972. * Returns the offset (integer).
  25973. */
  25974. VertexBuffer.prototype.getOffset = function () {
  25975. return this._offset;
  25976. };
  25977. /**
  25978. * Returns the VertexBuffer total size (integer).
  25979. */
  25980. VertexBuffer.prototype.getSize = function () {
  25981. return this._size;
  25982. };
  25983. /**
  25984. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25985. */
  25986. VertexBuffer.prototype.getIsInstanced = function () {
  25987. return this._instanced;
  25988. };
  25989. /**
  25990. * Returns the instancing divisor, zero for non-instanced (integer).
  25991. */
  25992. VertexBuffer.prototype.getInstanceDivisor = function () {
  25993. return this._instanceDivisor;
  25994. };
  25995. // Methods
  25996. /**
  25997. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25998. * Returns the created WebGLBuffer.
  25999. */
  26000. VertexBuffer.prototype.create = function (data) {
  26001. return this._buffer.create(data);
  26002. };
  26003. /**
  26004. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26005. * This function will create a new buffer if the current one is not updatable
  26006. * Returns the updated WebGLBuffer.
  26007. */
  26008. VertexBuffer.prototype.update = function (data) {
  26009. return this._buffer.update(data);
  26010. };
  26011. /**
  26012. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26013. * Returns the directly updated WebGLBuffer.
  26014. */
  26015. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26016. return this._buffer.updateDirectly(data, offset);
  26017. };
  26018. /**
  26019. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26020. */
  26021. VertexBuffer.prototype.dispose = function () {
  26022. if (this._ownsBuffer) {
  26023. this._buffer.dispose();
  26024. }
  26025. };
  26026. Object.defineProperty(VertexBuffer, "PositionKind", {
  26027. get: function () {
  26028. return VertexBuffer._PositionKind;
  26029. },
  26030. enumerable: true,
  26031. configurable: true
  26032. });
  26033. Object.defineProperty(VertexBuffer, "NormalKind", {
  26034. get: function () {
  26035. return VertexBuffer._NormalKind;
  26036. },
  26037. enumerable: true,
  26038. configurable: true
  26039. });
  26040. Object.defineProperty(VertexBuffer, "TangentKind", {
  26041. get: function () {
  26042. return VertexBuffer._TangentKind;
  26043. },
  26044. enumerable: true,
  26045. configurable: true
  26046. });
  26047. Object.defineProperty(VertexBuffer, "UVKind", {
  26048. get: function () {
  26049. return VertexBuffer._UVKind;
  26050. },
  26051. enumerable: true,
  26052. configurable: true
  26053. });
  26054. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26055. get: function () {
  26056. return VertexBuffer._UV2Kind;
  26057. },
  26058. enumerable: true,
  26059. configurable: true
  26060. });
  26061. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26062. get: function () {
  26063. return VertexBuffer._UV3Kind;
  26064. },
  26065. enumerable: true,
  26066. configurable: true
  26067. });
  26068. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26069. get: function () {
  26070. return VertexBuffer._UV4Kind;
  26071. },
  26072. enumerable: true,
  26073. configurable: true
  26074. });
  26075. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26076. get: function () {
  26077. return VertexBuffer._UV5Kind;
  26078. },
  26079. enumerable: true,
  26080. configurable: true
  26081. });
  26082. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26083. get: function () {
  26084. return VertexBuffer._UV6Kind;
  26085. },
  26086. enumerable: true,
  26087. configurable: true
  26088. });
  26089. Object.defineProperty(VertexBuffer, "ColorKind", {
  26090. get: function () {
  26091. return VertexBuffer._ColorKind;
  26092. },
  26093. enumerable: true,
  26094. configurable: true
  26095. });
  26096. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26097. get: function () {
  26098. return VertexBuffer._MatricesIndicesKind;
  26099. },
  26100. enumerable: true,
  26101. configurable: true
  26102. });
  26103. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26104. get: function () {
  26105. return VertexBuffer._MatricesWeightsKind;
  26106. },
  26107. enumerable: true,
  26108. configurable: true
  26109. });
  26110. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26111. get: function () {
  26112. return VertexBuffer._MatricesIndicesExtraKind;
  26113. },
  26114. enumerable: true,
  26115. configurable: true
  26116. });
  26117. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26118. get: function () {
  26119. return VertexBuffer._MatricesWeightsExtraKind;
  26120. },
  26121. enumerable: true,
  26122. configurable: true
  26123. });
  26124. /**
  26125. * Deduces the stride given a kind.
  26126. * @param kind The kind string to deduce
  26127. * @returns The deduced stride
  26128. */
  26129. VertexBuffer.DeduceStride = function (kind) {
  26130. switch (kind) {
  26131. case VertexBuffer.UVKind:
  26132. case VertexBuffer.UV2Kind:
  26133. case VertexBuffer.UV3Kind:
  26134. case VertexBuffer.UV4Kind:
  26135. case VertexBuffer.UV5Kind:
  26136. case VertexBuffer.UV6Kind:
  26137. return 2;
  26138. case VertexBuffer.NormalKind:
  26139. case VertexBuffer.PositionKind:
  26140. return 3;
  26141. case VertexBuffer.ColorKind:
  26142. case VertexBuffer.MatricesIndicesKind:
  26143. case VertexBuffer.MatricesIndicesExtraKind:
  26144. case VertexBuffer.MatricesWeightsKind:
  26145. case VertexBuffer.MatricesWeightsExtraKind:
  26146. case VertexBuffer.TangentKind:
  26147. return 4;
  26148. default:
  26149. throw new Error("Invalid kind '" + kind + "'");
  26150. }
  26151. };
  26152. // Enums
  26153. VertexBuffer._PositionKind = "position";
  26154. VertexBuffer._NormalKind = "normal";
  26155. VertexBuffer._TangentKind = "tangent";
  26156. VertexBuffer._UVKind = "uv";
  26157. VertexBuffer._UV2Kind = "uv2";
  26158. VertexBuffer._UV3Kind = "uv3";
  26159. VertexBuffer._UV4Kind = "uv4";
  26160. VertexBuffer._UV5Kind = "uv5";
  26161. VertexBuffer._UV6Kind = "uv6";
  26162. VertexBuffer._ColorKind = "color";
  26163. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26164. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26165. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26166. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26167. return VertexBuffer;
  26168. }());
  26169. BABYLON.VertexBuffer = VertexBuffer;
  26170. })(BABYLON || (BABYLON = {}));
  26171. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26172. var BABYLON;
  26173. (function (BABYLON) {
  26174. /**
  26175. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26176. */
  26177. var DummyInternalTextureTracker = /** @class */ (function () {
  26178. function DummyInternalTextureTracker() {
  26179. /**
  26180. * Gets or set the previous tracker in the list
  26181. */
  26182. this.previous = null;
  26183. /**
  26184. * Gets or set the next tracker in the list
  26185. */
  26186. this.next = null;
  26187. }
  26188. return DummyInternalTextureTracker;
  26189. }());
  26190. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26191. })(BABYLON || (BABYLON = {}));
  26192. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26193. var BABYLON;
  26194. (function (BABYLON) {
  26195. /**
  26196. * Class used to store data associated with WebGL texture data for the engine
  26197. * This class should not be used directly
  26198. */
  26199. var InternalTexture = /** @class */ (function () {
  26200. /**
  26201. * Creates a new InternalTexture
  26202. * @param engine defines the engine to use
  26203. * @param dataSource defines the type of data that will be used
  26204. */
  26205. function InternalTexture(engine, dataSource) {
  26206. /**
  26207. * Observable called when the texture is loaded
  26208. */
  26209. this.onLoadedObservable = new BABYLON.Observable();
  26210. /**
  26211. * Gets or set the previous tracker in the list
  26212. */
  26213. this.previous = null;
  26214. /**
  26215. * Gets or set the next tracker in the list
  26216. */
  26217. this.next = null;
  26218. // Private
  26219. /** @ignore */
  26220. this._initialSlot = -1;
  26221. /** @ignore */
  26222. this._designatedSlot = -1;
  26223. /** @ignore */
  26224. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26225. /** @ignore */
  26226. this._comparisonFunction = 0;
  26227. /** @ignore */
  26228. this._references = 1;
  26229. this._engine = engine;
  26230. this._dataSource = dataSource;
  26231. this._webGLTexture = engine._createTexture();
  26232. }
  26233. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26234. /**
  26235. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26236. */
  26237. get: function () {
  26238. return this._dataSource;
  26239. },
  26240. enumerable: true,
  26241. configurable: true
  26242. });
  26243. /**
  26244. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26245. */
  26246. InternalTexture.prototype.incrementReferences = function () {
  26247. this._references++;
  26248. };
  26249. /**
  26250. * Change the size of the texture (not the size of the content)
  26251. * @param width defines the new width
  26252. * @param height defines the new height
  26253. * @param depth defines the new depth (1 by default)
  26254. */
  26255. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26256. if (depth === void 0) { depth = 1; }
  26257. this.width = width;
  26258. this.height = height;
  26259. this.depth = depth;
  26260. this.baseWidth = width;
  26261. this.baseHeight = height;
  26262. this.baseDepth = depth;
  26263. this._size = width * height * depth;
  26264. };
  26265. /** @ignore */
  26266. InternalTexture.prototype._rebuild = function () {
  26267. var _this = this;
  26268. var proxy;
  26269. this.isReady = false;
  26270. this._cachedCoordinatesMode = null;
  26271. this._cachedWrapU = null;
  26272. this._cachedWrapV = null;
  26273. this._cachedAnisotropicFilteringLevel = null;
  26274. switch (this._dataSource) {
  26275. case InternalTexture.DATASOURCE_TEMP:
  26276. return;
  26277. case InternalTexture.DATASOURCE_URL:
  26278. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26279. _this.isReady = true;
  26280. }, null, this._buffer, undefined, this.format);
  26281. proxy._swapAndDie(this);
  26282. return;
  26283. case InternalTexture.DATASOURCE_RAW:
  26284. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26285. proxy._swapAndDie(this);
  26286. this.isReady = true;
  26287. return;
  26288. case InternalTexture.DATASOURCE_RAW3D:
  26289. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26290. proxy._swapAndDie(this);
  26291. this.isReady = true;
  26292. return;
  26293. case InternalTexture.DATASOURCE_DYNAMIC:
  26294. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26295. proxy._swapAndDie(this);
  26296. // The engine will make sure to update content so no need to flag it as isReady = true
  26297. return;
  26298. case InternalTexture.DATASOURCE_RENDERTARGET:
  26299. var options = new BABYLON.RenderTargetCreationOptions();
  26300. options.generateDepthBuffer = this._generateDepthBuffer;
  26301. options.generateMipMaps = this.generateMipMaps;
  26302. options.generateStencilBuffer = this._generateStencilBuffer;
  26303. options.samplingMode = this.samplingMode;
  26304. options.type = this.type;
  26305. if (this.isCube) {
  26306. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26307. }
  26308. else {
  26309. var size = {
  26310. width: this.width,
  26311. height: this.height
  26312. };
  26313. proxy = this._engine.createRenderTargetTexture(size, options);
  26314. }
  26315. proxy._swapAndDie(this);
  26316. this.isReady = true;
  26317. return;
  26318. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26319. var depthTextureOptions = {
  26320. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26321. comparisonFunction: this._comparisonFunction,
  26322. generateStencil: this._generateStencilBuffer,
  26323. };
  26324. if (this.isCube) {
  26325. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26326. }
  26327. else {
  26328. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26329. }
  26330. proxy._swapAndDie(this);
  26331. this.isReady = true;
  26332. return;
  26333. case InternalTexture.DATASOURCE_CUBE:
  26334. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26335. _this.isReady = true;
  26336. }, null, this.format, this._extension);
  26337. proxy._swapAndDie(this);
  26338. return;
  26339. case InternalTexture.DATASOURCE_CUBERAW:
  26340. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26341. proxy._swapAndDie(this);
  26342. this.isReady = true;
  26343. return;
  26344. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26345. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26346. if (proxy) {
  26347. proxy._swapAndDie(_this);
  26348. }
  26349. _this.isReady = true;
  26350. }, null, this.format, this._extension);
  26351. return;
  26352. }
  26353. };
  26354. InternalTexture.prototype._swapAndDie = function (target) {
  26355. target._webGLTexture = this._webGLTexture;
  26356. if (this._framebuffer) {
  26357. target._framebuffer = this._framebuffer;
  26358. }
  26359. if (this._depthStencilBuffer) {
  26360. target._depthStencilBuffer = this._depthStencilBuffer;
  26361. }
  26362. if (this._lodTextureHigh) {
  26363. if (target._lodTextureHigh) {
  26364. target._lodTextureHigh.dispose();
  26365. }
  26366. target._lodTextureHigh = this._lodTextureHigh;
  26367. }
  26368. if (this._lodTextureMid) {
  26369. if (target._lodTextureMid) {
  26370. target._lodTextureMid.dispose();
  26371. }
  26372. target._lodTextureMid = this._lodTextureMid;
  26373. }
  26374. if (this._lodTextureLow) {
  26375. if (target._lodTextureLow) {
  26376. target._lodTextureLow.dispose();
  26377. }
  26378. target._lodTextureLow = this._lodTextureLow;
  26379. }
  26380. var cache = this._engine.getLoadedTexturesCache();
  26381. var index = cache.indexOf(this);
  26382. if (index !== -1) {
  26383. cache.splice(index, 1);
  26384. }
  26385. };
  26386. /**
  26387. * Dispose the current allocated resources
  26388. */
  26389. InternalTexture.prototype.dispose = function () {
  26390. if (!this._webGLTexture) {
  26391. return;
  26392. }
  26393. this._references--;
  26394. if (this._references === 0) {
  26395. this._engine._releaseTexture(this);
  26396. this._webGLTexture = null;
  26397. this.previous = null;
  26398. this.next = null;
  26399. }
  26400. };
  26401. /**
  26402. * The source of the texture data is unknown
  26403. */
  26404. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26405. /**
  26406. * Texture data comes from an URL
  26407. */
  26408. InternalTexture.DATASOURCE_URL = 1;
  26409. /**
  26410. * Texture data is only used for temporary storage
  26411. */
  26412. InternalTexture.DATASOURCE_TEMP = 2;
  26413. /**
  26414. * Texture data comes from raw data (ArrayBuffer)
  26415. */
  26416. InternalTexture.DATASOURCE_RAW = 3;
  26417. /**
  26418. * Texture content is dynamic (video or dynamic texture)
  26419. */
  26420. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26421. /**
  26422. * Texture content is generated by rendering to it
  26423. */
  26424. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26425. /**
  26426. * Texture content is part of a multi render target process
  26427. */
  26428. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26429. /**
  26430. * Texture data comes from a cube data file
  26431. */
  26432. InternalTexture.DATASOURCE_CUBE = 7;
  26433. /**
  26434. * Texture data comes from a raw cube data
  26435. */
  26436. InternalTexture.DATASOURCE_CUBERAW = 8;
  26437. /**
  26438. * Texture data come from a prefiltered cube data file
  26439. */
  26440. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26441. /**
  26442. * Texture content is raw 3D data
  26443. */
  26444. InternalTexture.DATASOURCE_RAW3D = 10;
  26445. /**
  26446. * Texture content is a depth texture
  26447. */
  26448. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26449. return InternalTexture;
  26450. }());
  26451. BABYLON.InternalTexture = InternalTexture;
  26452. })(BABYLON || (BABYLON = {}));
  26453. //# sourceMappingURL=babylon.internalTexture.js.map
  26454. var BABYLON;
  26455. (function (BABYLON) {
  26456. var BaseTexture = /** @class */ (function () {
  26457. function BaseTexture(scene) {
  26458. this._hasAlpha = false;
  26459. this.getAlphaFromRGB = false;
  26460. this.level = 1;
  26461. this.coordinatesIndex = 0;
  26462. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26463. /**
  26464. * | Value | Type | Description |
  26465. * | ----- | ------------------ | ----------- |
  26466. * | 0 | CLAMP_ADDRESSMODE | |
  26467. * | 1 | WRAP_ADDRESSMODE | |
  26468. * | 2 | MIRROR_ADDRESSMODE | |
  26469. */
  26470. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26471. /**
  26472. * | Value | Type | Description |
  26473. * | ----- | ------------------ | ----------- |
  26474. * | 0 | CLAMP_ADDRESSMODE | |
  26475. * | 1 | WRAP_ADDRESSMODE | |
  26476. * | 2 | MIRROR_ADDRESSMODE | |
  26477. */
  26478. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26479. /**
  26480. * | Value | Type | Description |
  26481. * | ----- | ------------------ | ----------- |
  26482. * | 0 | CLAMP_ADDRESSMODE | |
  26483. * | 1 | WRAP_ADDRESSMODE | |
  26484. * | 2 | MIRROR_ADDRESSMODE | |
  26485. */
  26486. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26487. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26488. this.isCube = false;
  26489. this.is3D = false;
  26490. this.gammaSpace = true;
  26491. this.invertZ = false;
  26492. this.lodLevelInAlpha = false;
  26493. this.lodGenerationOffset = 0.0;
  26494. this.lodGenerationScale = 0.8;
  26495. this.isRenderTarget = false;
  26496. this.animations = new Array();
  26497. /**
  26498. * An event triggered when the texture is disposed.
  26499. * @type {BABYLON.Observable}
  26500. */
  26501. this.onDisposeObservable = new BABYLON.Observable();
  26502. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26503. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26504. if (this._scene) {
  26505. this._scene.textures.push(this);
  26506. }
  26507. this._uid = null;
  26508. }
  26509. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26510. get: function () {
  26511. return this._hasAlpha;
  26512. },
  26513. set: function (value) {
  26514. if (this._hasAlpha === value) {
  26515. return;
  26516. }
  26517. this._hasAlpha = value;
  26518. if (this._scene) {
  26519. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26520. }
  26521. },
  26522. enumerable: true,
  26523. configurable: true
  26524. });
  26525. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26526. get: function () {
  26527. return this._coordinatesMode;
  26528. },
  26529. /**
  26530. * How a texture is mapped.
  26531. *
  26532. * | Value | Type | Description |
  26533. * | ----- | ----------------------------------- | ----------- |
  26534. * | 0 | EXPLICIT_MODE | |
  26535. * | 1 | SPHERICAL_MODE | |
  26536. * | 2 | PLANAR_MODE | |
  26537. * | 3 | CUBIC_MODE | |
  26538. * | 4 | PROJECTION_MODE | |
  26539. * | 5 | SKYBOX_MODE | |
  26540. * | 6 | INVCUBIC_MODE | |
  26541. * | 7 | EQUIRECTANGULAR_MODE | |
  26542. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26543. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26544. */
  26545. set: function (value) {
  26546. if (this._coordinatesMode === value) {
  26547. return;
  26548. }
  26549. this._coordinatesMode = value;
  26550. if (this._scene) {
  26551. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26552. }
  26553. },
  26554. enumerable: true,
  26555. configurable: true
  26556. });
  26557. Object.defineProperty(BaseTexture.prototype, "uid", {
  26558. get: function () {
  26559. if (!this._uid) {
  26560. this._uid = BABYLON.Tools.RandomId();
  26561. }
  26562. return this._uid;
  26563. },
  26564. enumerable: true,
  26565. configurable: true
  26566. });
  26567. BaseTexture.prototype.toString = function () {
  26568. return this.name;
  26569. };
  26570. BaseTexture.prototype.getClassName = function () {
  26571. return "BaseTexture";
  26572. };
  26573. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26574. set: function (callback) {
  26575. if (this._onDisposeObserver) {
  26576. this.onDisposeObservable.remove(this._onDisposeObserver);
  26577. }
  26578. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26579. },
  26580. enumerable: true,
  26581. configurable: true
  26582. });
  26583. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26584. get: function () {
  26585. return true;
  26586. },
  26587. enumerable: true,
  26588. configurable: true
  26589. });
  26590. BaseTexture.prototype.getScene = function () {
  26591. return this._scene;
  26592. };
  26593. BaseTexture.prototype.getTextureMatrix = function () {
  26594. return BABYLON.Matrix.IdentityReadOnly;
  26595. };
  26596. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26597. return BABYLON.Matrix.IdentityReadOnly;
  26598. };
  26599. BaseTexture.prototype.getInternalTexture = function () {
  26600. return this._texture;
  26601. };
  26602. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26603. return !this.isBlocking || this.isReady();
  26604. };
  26605. BaseTexture.prototype.isReady = function () {
  26606. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26607. this.delayLoad();
  26608. return false;
  26609. }
  26610. if (this._texture) {
  26611. return this._texture.isReady;
  26612. }
  26613. return false;
  26614. };
  26615. BaseTexture.prototype.getSize = function () {
  26616. if (this._texture && this._texture.width) {
  26617. return new BABYLON.Size(this._texture.width, this._texture.height);
  26618. }
  26619. if (this._texture && this._texture._size) {
  26620. return new BABYLON.Size(this._texture._size, this._texture._size);
  26621. }
  26622. return BABYLON.Size.Zero();
  26623. };
  26624. BaseTexture.prototype.getBaseSize = function () {
  26625. if (!this.isReady() || !this._texture)
  26626. return BABYLON.Size.Zero();
  26627. if (this._texture._size) {
  26628. return new BABYLON.Size(this._texture._size, this._texture._size);
  26629. }
  26630. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26631. };
  26632. BaseTexture.prototype.scale = function (ratio) {
  26633. };
  26634. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26635. get: function () {
  26636. return false;
  26637. },
  26638. enumerable: true,
  26639. configurable: true
  26640. });
  26641. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26642. if (!this._scene) {
  26643. return null;
  26644. }
  26645. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26646. for (var index = 0; index < texturesCache.length; index++) {
  26647. var texturesCacheEntry = texturesCache[index];
  26648. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26649. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26650. texturesCacheEntry.incrementReferences();
  26651. return texturesCacheEntry;
  26652. }
  26653. }
  26654. }
  26655. return null;
  26656. };
  26657. BaseTexture.prototype._rebuild = function () {
  26658. };
  26659. BaseTexture.prototype.delayLoad = function () {
  26660. };
  26661. BaseTexture.prototype.clone = function () {
  26662. return null;
  26663. };
  26664. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26665. get: function () {
  26666. if (!this._texture) {
  26667. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26668. }
  26669. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26670. },
  26671. enumerable: true,
  26672. configurable: true
  26673. });
  26674. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26675. get: function () {
  26676. if (!this._texture) {
  26677. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26678. }
  26679. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26680. },
  26681. enumerable: true,
  26682. configurable: true
  26683. });
  26684. BaseTexture.prototype.readPixels = function (faceIndex) {
  26685. if (faceIndex === void 0) { faceIndex = 0; }
  26686. if (!this._texture) {
  26687. return null;
  26688. }
  26689. var size = this.getSize();
  26690. var scene = this.getScene();
  26691. if (!scene) {
  26692. return null;
  26693. }
  26694. var engine = scene.getEngine();
  26695. if (this._texture.isCube) {
  26696. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26697. }
  26698. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26699. };
  26700. BaseTexture.prototype.releaseInternalTexture = function () {
  26701. if (this._texture) {
  26702. this._texture.dispose();
  26703. this._texture = null;
  26704. }
  26705. };
  26706. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26707. get: function () {
  26708. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26709. return null;
  26710. }
  26711. if (!this._texture._sphericalPolynomial) {
  26712. this._texture._sphericalPolynomial =
  26713. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26714. }
  26715. return this._texture._sphericalPolynomial;
  26716. },
  26717. set: function (value) {
  26718. if (this._texture) {
  26719. this._texture._sphericalPolynomial = value;
  26720. }
  26721. },
  26722. enumerable: true,
  26723. configurable: true
  26724. });
  26725. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26726. get: function () {
  26727. if (this._texture) {
  26728. return this._texture._lodTextureHigh;
  26729. }
  26730. return null;
  26731. },
  26732. enumerable: true,
  26733. configurable: true
  26734. });
  26735. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26736. get: function () {
  26737. if (this._texture) {
  26738. return this._texture._lodTextureMid;
  26739. }
  26740. return null;
  26741. },
  26742. enumerable: true,
  26743. configurable: true
  26744. });
  26745. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26746. get: function () {
  26747. if (this._texture) {
  26748. return this._texture._lodTextureLow;
  26749. }
  26750. return null;
  26751. },
  26752. enumerable: true,
  26753. configurable: true
  26754. });
  26755. BaseTexture.prototype.dispose = function () {
  26756. if (!this._scene) {
  26757. return;
  26758. }
  26759. // Animations
  26760. this._scene.stopAnimation(this);
  26761. // Remove from scene
  26762. this._scene._removePendingData(this);
  26763. var index = this._scene.textures.indexOf(this);
  26764. if (index >= 0) {
  26765. this._scene.textures.splice(index, 1);
  26766. }
  26767. if (this._texture === undefined) {
  26768. return;
  26769. }
  26770. // Release
  26771. this.releaseInternalTexture();
  26772. // Callback
  26773. this.onDisposeObservable.notifyObservers(this);
  26774. this.onDisposeObservable.clear();
  26775. };
  26776. BaseTexture.prototype.serialize = function () {
  26777. if (!this.name) {
  26778. return null;
  26779. }
  26780. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26781. // Animations
  26782. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26783. return serializationObject;
  26784. };
  26785. BaseTexture.WhenAllReady = function (textures, callback) {
  26786. var numRemaining = textures.length;
  26787. if (numRemaining === 0) {
  26788. callback();
  26789. return;
  26790. }
  26791. var _loop_1 = function () {
  26792. texture = textures[i];
  26793. if (texture.isReady()) {
  26794. if (--numRemaining === 0) {
  26795. callback();
  26796. }
  26797. }
  26798. else {
  26799. onLoadObservable = texture.onLoadObservable;
  26800. var onLoadCallback_1 = function () {
  26801. onLoadObservable.removeCallback(onLoadCallback_1);
  26802. if (--numRemaining === 0) {
  26803. callback();
  26804. }
  26805. };
  26806. onLoadObservable.add(onLoadCallback_1);
  26807. }
  26808. };
  26809. var texture, onLoadObservable;
  26810. for (var i = 0; i < textures.length; i++) {
  26811. _loop_1();
  26812. }
  26813. };
  26814. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26815. __decorate([
  26816. BABYLON.serialize()
  26817. ], BaseTexture.prototype, "name", void 0);
  26818. __decorate([
  26819. BABYLON.serialize("hasAlpha")
  26820. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26821. __decorate([
  26822. BABYLON.serialize()
  26823. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26824. __decorate([
  26825. BABYLON.serialize()
  26826. ], BaseTexture.prototype, "level", void 0);
  26827. __decorate([
  26828. BABYLON.serialize()
  26829. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26830. __decorate([
  26831. BABYLON.serialize("coordinatesMode")
  26832. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26833. __decorate([
  26834. BABYLON.serialize()
  26835. ], BaseTexture.prototype, "wrapU", void 0);
  26836. __decorate([
  26837. BABYLON.serialize()
  26838. ], BaseTexture.prototype, "wrapV", void 0);
  26839. __decorate([
  26840. BABYLON.serialize()
  26841. ], BaseTexture.prototype, "wrapR", void 0);
  26842. __decorate([
  26843. BABYLON.serialize()
  26844. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26845. __decorate([
  26846. BABYLON.serialize()
  26847. ], BaseTexture.prototype, "isCube", void 0);
  26848. __decorate([
  26849. BABYLON.serialize()
  26850. ], BaseTexture.prototype, "is3D", void 0);
  26851. __decorate([
  26852. BABYLON.serialize()
  26853. ], BaseTexture.prototype, "gammaSpace", void 0);
  26854. __decorate([
  26855. BABYLON.serialize()
  26856. ], BaseTexture.prototype, "invertZ", void 0);
  26857. __decorate([
  26858. BABYLON.serialize()
  26859. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26860. __decorate([
  26861. BABYLON.serialize()
  26862. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26863. __decorate([
  26864. BABYLON.serialize()
  26865. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26866. __decorate([
  26867. BABYLON.serialize()
  26868. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26869. return BaseTexture;
  26870. }());
  26871. BABYLON.BaseTexture = BaseTexture;
  26872. })(BABYLON || (BABYLON = {}));
  26873. //# sourceMappingURL=babylon.baseTexture.js.map
  26874. var BABYLON;
  26875. (function (BABYLON) {
  26876. var Texture = /** @class */ (function (_super) {
  26877. __extends(Texture, _super);
  26878. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26879. if (noMipmap === void 0) { noMipmap = false; }
  26880. if (invertY === void 0) { invertY = true; }
  26881. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26882. if (onLoad === void 0) { onLoad = null; }
  26883. if (onError === void 0) { onError = null; }
  26884. if (buffer === void 0) { buffer = null; }
  26885. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26886. var _this = _super.call(this, scene) || this;
  26887. _this.uOffset = 0;
  26888. _this.vOffset = 0;
  26889. _this.uScale = 1.0;
  26890. _this.vScale = 1.0;
  26891. _this.uAng = 0;
  26892. _this.vAng = 0;
  26893. _this.wAng = 0;
  26894. _this._isBlocking = true;
  26895. _this.name = url || "";
  26896. _this.url = url;
  26897. _this._noMipmap = noMipmap;
  26898. _this._invertY = invertY;
  26899. _this._samplingMode = samplingMode;
  26900. _this._buffer = buffer;
  26901. _this._deleteBuffer = deleteBuffer;
  26902. if (format) {
  26903. _this._format = format;
  26904. }
  26905. scene = _this.getScene();
  26906. if (!scene) {
  26907. return _this;
  26908. }
  26909. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26910. var load = function () {
  26911. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26912. _this.onLoadObservable.notifyObservers(_this);
  26913. }
  26914. if (onLoad) {
  26915. onLoad();
  26916. }
  26917. if (!_this.isBlocking && scene) {
  26918. scene.resetCachedMaterial();
  26919. }
  26920. };
  26921. if (!_this.url) {
  26922. _this._delayedOnLoad = load;
  26923. _this._delayedOnError = onError;
  26924. return _this;
  26925. }
  26926. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26927. if (!_this._texture) {
  26928. if (!scene.useDelayedTextureLoading) {
  26929. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26930. if (deleteBuffer) {
  26931. delete _this._buffer;
  26932. }
  26933. }
  26934. else {
  26935. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26936. _this._delayedOnLoad = load;
  26937. _this._delayedOnError = onError;
  26938. }
  26939. }
  26940. else {
  26941. if (_this._texture.isReady) {
  26942. BABYLON.Tools.SetImmediate(function () { return load(); });
  26943. }
  26944. else {
  26945. _this._texture.onLoadedObservable.add(load);
  26946. }
  26947. }
  26948. return _this;
  26949. }
  26950. Object.defineProperty(Texture.prototype, "noMipmap", {
  26951. get: function () {
  26952. return this._noMipmap;
  26953. },
  26954. enumerable: true,
  26955. configurable: true
  26956. });
  26957. Object.defineProperty(Texture.prototype, "isBlocking", {
  26958. get: function () {
  26959. return this._isBlocking;
  26960. },
  26961. set: function (value) {
  26962. this._isBlocking = value;
  26963. },
  26964. enumerable: true,
  26965. configurable: true
  26966. });
  26967. Object.defineProperty(Texture.prototype, "samplingMode", {
  26968. get: function () {
  26969. return this._samplingMode;
  26970. },
  26971. enumerable: true,
  26972. configurable: true
  26973. });
  26974. Texture.prototype.updateURL = function (url) {
  26975. this.url = url;
  26976. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26977. this.delayLoad();
  26978. };
  26979. Texture.prototype.delayLoad = function () {
  26980. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26981. return;
  26982. }
  26983. var scene = this.getScene();
  26984. if (!scene) {
  26985. return;
  26986. }
  26987. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26988. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26989. if (!this._texture) {
  26990. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26991. if (this._deleteBuffer) {
  26992. delete this._buffer;
  26993. }
  26994. }
  26995. else {
  26996. if (this._delayedOnLoad) {
  26997. if (this._texture.isReady) {
  26998. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26999. }
  27000. else {
  27001. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27002. }
  27003. }
  27004. }
  27005. this._delayedOnLoad = null;
  27006. this._delayedOnError = null;
  27007. };
  27008. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27009. if (!this._texture) {
  27010. return;
  27011. }
  27012. var scene = this.getScene();
  27013. if (!scene) {
  27014. return;
  27015. }
  27016. this._samplingMode = samplingMode;
  27017. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27018. };
  27019. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27020. x *= this.uScale;
  27021. y *= this.vScale;
  27022. x -= 0.5 * this.uScale;
  27023. y -= 0.5 * this.vScale;
  27024. z -= 0.5;
  27025. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27026. t.x += 0.5 * this.uScale + this.uOffset;
  27027. t.y += 0.5 * this.vScale + this.vOffset;
  27028. t.z += 0.5;
  27029. };
  27030. Texture.prototype.getTextureMatrix = function () {
  27031. var _this = this;
  27032. if (this.uOffset === this._cachedUOffset &&
  27033. this.vOffset === this._cachedVOffset &&
  27034. this.uScale === this._cachedUScale &&
  27035. this.vScale === this._cachedVScale &&
  27036. this.uAng === this._cachedUAng &&
  27037. this.vAng === this._cachedVAng &&
  27038. this.wAng === this._cachedWAng) {
  27039. return this._cachedTextureMatrix;
  27040. }
  27041. this._cachedUOffset = this.uOffset;
  27042. this._cachedVOffset = this.vOffset;
  27043. this._cachedUScale = this.uScale;
  27044. this._cachedVScale = this.vScale;
  27045. this._cachedUAng = this.uAng;
  27046. this._cachedVAng = this.vAng;
  27047. this._cachedWAng = this.wAng;
  27048. if (!this._cachedTextureMatrix) {
  27049. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27050. this._rowGenerationMatrix = new BABYLON.Matrix();
  27051. this._t0 = BABYLON.Vector3.Zero();
  27052. this._t1 = BABYLON.Vector3.Zero();
  27053. this._t2 = BABYLON.Vector3.Zero();
  27054. }
  27055. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27056. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27057. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27058. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27059. this._t1.subtractInPlace(this._t0);
  27060. this._t2.subtractInPlace(this._t0);
  27061. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27062. this._cachedTextureMatrix.m[0] = this._t1.x;
  27063. this._cachedTextureMatrix.m[1] = this._t1.y;
  27064. this._cachedTextureMatrix.m[2] = this._t1.z;
  27065. this._cachedTextureMatrix.m[4] = this._t2.x;
  27066. this._cachedTextureMatrix.m[5] = this._t2.y;
  27067. this._cachedTextureMatrix.m[6] = this._t2.z;
  27068. this._cachedTextureMatrix.m[8] = this._t0.x;
  27069. this._cachedTextureMatrix.m[9] = this._t0.y;
  27070. this._cachedTextureMatrix.m[10] = this._t0.z;
  27071. var scene = this.getScene();
  27072. if (!scene) {
  27073. return this._cachedTextureMatrix;
  27074. }
  27075. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27076. return mat.hasTexture(_this);
  27077. });
  27078. return this._cachedTextureMatrix;
  27079. };
  27080. Texture.prototype.getReflectionTextureMatrix = function () {
  27081. var _this = this;
  27082. var scene = this.getScene();
  27083. if (!scene) {
  27084. return this._cachedTextureMatrix;
  27085. }
  27086. if (this.uOffset === this._cachedUOffset &&
  27087. this.vOffset === this._cachedVOffset &&
  27088. this.uScale === this._cachedUScale &&
  27089. this.vScale === this._cachedVScale &&
  27090. this.coordinatesMode === this._cachedCoordinatesMode) {
  27091. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27092. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27093. return this._cachedTextureMatrix;
  27094. }
  27095. }
  27096. else {
  27097. return this._cachedTextureMatrix;
  27098. }
  27099. }
  27100. if (!this._cachedTextureMatrix) {
  27101. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27102. }
  27103. if (!this._projectionModeMatrix) {
  27104. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27105. }
  27106. this._cachedUOffset = this.uOffset;
  27107. this._cachedVOffset = this.vOffset;
  27108. this._cachedUScale = this.uScale;
  27109. this._cachedVScale = this.vScale;
  27110. this._cachedCoordinatesMode = this.coordinatesMode;
  27111. switch (this.coordinatesMode) {
  27112. case Texture.PLANAR_MODE:
  27113. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27114. this._cachedTextureMatrix[0] = this.uScale;
  27115. this._cachedTextureMatrix[5] = this.vScale;
  27116. this._cachedTextureMatrix[12] = this.uOffset;
  27117. this._cachedTextureMatrix[13] = this.vOffset;
  27118. break;
  27119. case Texture.PROJECTION_MODE:
  27120. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27121. this._projectionModeMatrix.m[0] = 0.5;
  27122. this._projectionModeMatrix.m[5] = -0.5;
  27123. this._projectionModeMatrix.m[10] = 0.0;
  27124. this._projectionModeMatrix.m[12] = 0.5;
  27125. this._projectionModeMatrix.m[13] = 0.5;
  27126. this._projectionModeMatrix.m[14] = 1.0;
  27127. this._projectionModeMatrix.m[15] = 1.0;
  27128. var projectionMatrix = scene.getProjectionMatrix();
  27129. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27130. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27131. break;
  27132. default:
  27133. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27134. break;
  27135. }
  27136. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27137. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27138. });
  27139. return this._cachedTextureMatrix;
  27140. };
  27141. Texture.prototype.clone = function () {
  27142. var _this = this;
  27143. return BABYLON.SerializationHelper.Clone(function () {
  27144. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27145. }, this);
  27146. };
  27147. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27148. get: function () {
  27149. if (!this._onLoadObservable) {
  27150. this._onLoadObservable = new BABYLON.Observable();
  27151. }
  27152. return this._onLoadObservable;
  27153. },
  27154. enumerable: true,
  27155. configurable: true
  27156. });
  27157. Texture.prototype.serialize = function () {
  27158. var serializationObject = _super.prototype.serialize.call(this);
  27159. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27160. serializationObject.base64String = this._buffer;
  27161. serializationObject.name = serializationObject.name.replace("data:", "");
  27162. }
  27163. return serializationObject;
  27164. };
  27165. Texture.prototype.getClassName = function () {
  27166. return "Texture";
  27167. };
  27168. Texture.prototype.dispose = function () {
  27169. _super.prototype.dispose.call(this);
  27170. if (this.onLoadObservable) {
  27171. this.onLoadObservable.clear();
  27172. this._onLoadObservable = null;
  27173. }
  27174. this._delayedOnLoad = null;
  27175. this._delayedOnError = null;
  27176. };
  27177. // Statics
  27178. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27179. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27180. if (onLoad === void 0) { onLoad = null; }
  27181. if (onError === void 0) { onError = null; }
  27182. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27183. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27184. };
  27185. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27186. if (parsedTexture.customType) {
  27187. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27188. // Update Sampling Mode
  27189. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27190. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27191. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27192. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27193. }
  27194. }
  27195. return parsedCustomTexture;
  27196. }
  27197. if (parsedTexture.isCube) {
  27198. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27199. }
  27200. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27201. return null;
  27202. }
  27203. var texture = BABYLON.SerializationHelper.Parse(function () {
  27204. var generateMipMaps = true;
  27205. if (parsedTexture.noMipmap) {
  27206. generateMipMaps = false;
  27207. }
  27208. if (parsedTexture.mirrorPlane) {
  27209. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27210. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27211. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27212. return mirrorTexture;
  27213. }
  27214. else if (parsedTexture.isRenderTarget) {
  27215. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27216. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27217. return renderTargetTexture;
  27218. }
  27219. else {
  27220. var texture;
  27221. if (parsedTexture.base64String) {
  27222. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27223. }
  27224. else {
  27225. var url = rootUrl + parsedTexture.name;
  27226. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27227. url = parsedTexture.url;
  27228. }
  27229. texture = new Texture(url, scene, !generateMipMaps);
  27230. }
  27231. return texture;
  27232. }
  27233. }, parsedTexture, scene);
  27234. // Update Sampling Mode
  27235. if (parsedTexture.samplingMode) {
  27236. var sampling = parsedTexture.samplingMode;
  27237. if (texture._samplingMode !== sampling) {
  27238. texture.updateSamplingMode(sampling);
  27239. }
  27240. }
  27241. // Animations
  27242. if (parsedTexture.animations) {
  27243. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27244. var parsedAnimation = parsedTexture.animations[animationIndex];
  27245. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27246. }
  27247. }
  27248. return texture;
  27249. };
  27250. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27251. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27252. if (noMipmap === void 0) { noMipmap = false; }
  27253. if (invertY === void 0) { invertY = true; }
  27254. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27255. if (onLoad === void 0) { onLoad = null; }
  27256. if (onError === void 0) { onError = null; }
  27257. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27258. if (name.substr(0, 5) !== "data:") {
  27259. name = "data:" + name;
  27260. }
  27261. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27262. };
  27263. // Constants
  27264. Texture.NEAREST_SAMPLINGMODE = 1;
  27265. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27266. Texture.BILINEAR_SAMPLINGMODE = 2;
  27267. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27268. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27269. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27270. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27271. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27272. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27273. Texture.NEAREST_LINEAR = 7;
  27274. Texture.NEAREST_NEAREST = 8;
  27275. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27276. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27277. Texture.LINEAR_LINEAR = 11;
  27278. Texture.LINEAR_NEAREST = 12;
  27279. Texture.EXPLICIT_MODE = 0;
  27280. Texture.SPHERICAL_MODE = 1;
  27281. Texture.PLANAR_MODE = 2;
  27282. Texture.CUBIC_MODE = 3;
  27283. Texture.PROJECTION_MODE = 4;
  27284. Texture.SKYBOX_MODE = 5;
  27285. Texture.INVCUBIC_MODE = 6;
  27286. Texture.EQUIRECTANGULAR_MODE = 7;
  27287. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27288. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27289. Texture.CLAMP_ADDRESSMODE = 0;
  27290. Texture.WRAP_ADDRESSMODE = 1;
  27291. Texture.MIRROR_ADDRESSMODE = 2;
  27292. /**
  27293. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  27294. */
  27295. Texture.UseSerializedUrlIfAny = false;
  27296. __decorate([
  27297. BABYLON.serialize()
  27298. ], Texture.prototype, "url", void 0);
  27299. __decorate([
  27300. BABYLON.serialize()
  27301. ], Texture.prototype, "uOffset", void 0);
  27302. __decorate([
  27303. BABYLON.serialize()
  27304. ], Texture.prototype, "vOffset", void 0);
  27305. __decorate([
  27306. BABYLON.serialize()
  27307. ], Texture.prototype, "uScale", void 0);
  27308. __decorate([
  27309. BABYLON.serialize()
  27310. ], Texture.prototype, "vScale", void 0);
  27311. __decorate([
  27312. BABYLON.serialize()
  27313. ], Texture.prototype, "uAng", void 0);
  27314. __decorate([
  27315. BABYLON.serialize()
  27316. ], Texture.prototype, "vAng", void 0);
  27317. __decorate([
  27318. BABYLON.serialize()
  27319. ], Texture.prototype, "wAng", void 0);
  27320. __decorate([
  27321. BABYLON.serialize()
  27322. ], Texture.prototype, "isBlocking", null);
  27323. return Texture;
  27324. }(BABYLON.BaseTexture));
  27325. BABYLON.Texture = Texture;
  27326. })(BABYLON || (BABYLON = {}));
  27327. //# sourceMappingURL=babylon.texture.js.map
  27328. var BABYLON;
  27329. (function (BABYLON) {
  27330. var _InstancesBatch = /** @class */ (function () {
  27331. function _InstancesBatch() {
  27332. this.mustReturn = false;
  27333. this.visibleInstances = new Array();
  27334. this.renderSelf = new Array();
  27335. }
  27336. return _InstancesBatch;
  27337. }());
  27338. BABYLON._InstancesBatch = _InstancesBatch;
  27339. var Mesh = /** @class */ (function (_super) {
  27340. __extends(Mesh, _super);
  27341. /**
  27342. * @constructor
  27343. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27344. * @param {Scene} scene The scene to add this mesh to.
  27345. * @param {Node} parent The parent of this mesh, if it has one
  27346. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27347. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27348. * When false, achieved by calling a clone(), also passing False.
  27349. * This will make creation of children, recursive.
  27350. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27351. */
  27352. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27353. if (scene === void 0) { scene = null; }
  27354. if (parent === void 0) { parent = null; }
  27355. if (source === void 0) { source = null; }
  27356. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27357. var _this = _super.call(this, name, scene) || this;
  27358. // Events
  27359. /**
  27360. * An event triggered before rendering the mesh
  27361. * @type {BABYLON.Observable}
  27362. */
  27363. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27364. /**
  27365. * An event triggered after rendering the mesh
  27366. * @type {BABYLON.Observable}
  27367. */
  27368. _this.onAfterRenderObservable = new BABYLON.Observable();
  27369. /**
  27370. * An event triggered before drawing the mesh
  27371. * @type {BABYLON.Observable}
  27372. */
  27373. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27374. // Members
  27375. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27376. _this.instances = new Array();
  27377. _this._LODLevels = new Array();
  27378. _this._visibleInstances = {};
  27379. _this._renderIdForInstances = new Array();
  27380. _this._batchCache = new _InstancesBatch();
  27381. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27382. // Use by builder only to know what orientation were the mesh build in.
  27383. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27384. _this.overrideMaterialSideOrientation = null;
  27385. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27386. // Will be used to save a source mesh reference, If any
  27387. _this._source = null;
  27388. scene = _this.getScene();
  27389. if (source) {
  27390. // Source mesh
  27391. _this._source = source;
  27392. // Geometry
  27393. if (source._geometry) {
  27394. source._geometry.applyToMesh(_this);
  27395. }
  27396. // Deep copy
  27397. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27398. // Metadata
  27399. if (source.metadata && source.metadata.clone) {
  27400. _this.metadata = source.metadata.clone();
  27401. }
  27402. else {
  27403. _this.metadata = source.metadata;
  27404. }
  27405. // Tags
  27406. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27407. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27408. }
  27409. // Parent
  27410. _this.parent = source.parent;
  27411. // Pivot
  27412. _this.setPivotMatrix(source.getPivotMatrix());
  27413. _this.id = name + "." + source.id;
  27414. // Material
  27415. _this.material = source.material;
  27416. var index;
  27417. if (!doNotCloneChildren) {
  27418. // Children
  27419. var directDescendants = source.getDescendants(true);
  27420. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27421. var child = directDescendants[index_1];
  27422. if (child.clone) {
  27423. child.clone(name + "." + child.name, _this);
  27424. }
  27425. }
  27426. }
  27427. // Physics clone
  27428. var physicsEngine = _this.getScene().getPhysicsEngine();
  27429. if (clonePhysicsImpostor && physicsEngine) {
  27430. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27431. if (impostor) {
  27432. _this.physicsImpostor = impostor.clone(_this);
  27433. }
  27434. }
  27435. // Particles
  27436. for (index = 0; index < scene.particleSystems.length; index++) {
  27437. var system = scene.particleSystems[index];
  27438. if (system.emitter === source) {
  27439. system.clone(system.name, _this);
  27440. }
  27441. }
  27442. _this.computeWorldMatrix(true);
  27443. }
  27444. // Parent
  27445. if (parent !== null) {
  27446. _this.parent = parent;
  27447. }
  27448. return _this;
  27449. }
  27450. Object.defineProperty(Mesh, "FRONTSIDE", {
  27451. /**
  27452. * Mesh side orientation : usually the external or front surface
  27453. */
  27454. get: function () {
  27455. return Mesh._FRONTSIDE;
  27456. },
  27457. enumerable: true,
  27458. configurable: true
  27459. });
  27460. Object.defineProperty(Mesh, "BACKSIDE", {
  27461. /**
  27462. * Mesh side orientation : usually the internal or back surface
  27463. */
  27464. get: function () {
  27465. return Mesh._BACKSIDE;
  27466. },
  27467. enumerable: true,
  27468. configurable: true
  27469. });
  27470. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27471. /**
  27472. * Mesh side orientation : both internal and external or front and back surfaces
  27473. */
  27474. get: function () {
  27475. return Mesh._DOUBLESIDE;
  27476. },
  27477. enumerable: true,
  27478. configurable: true
  27479. });
  27480. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27481. /**
  27482. * Mesh side orientation : by default, `FRONTSIDE`
  27483. */
  27484. get: function () {
  27485. return Mesh._DEFAULTSIDE;
  27486. },
  27487. enumerable: true,
  27488. configurable: true
  27489. });
  27490. Object.defineProperty(Mesh, "NO_CAP", {
  27491. /**
  27492. * Mesh cap setting : no cap
  27493. */
  27494. get: function () {
  27495. return Mesh._NO_CAP;
  27496. },
  27497. enumerable: true,
  27498. configurable: true
  27499. });
  27500. Object.defineProperty(Mesh, "CAP_START", {
  27501. /**
  27502. * Mesh cap setting : one cap at the beginning of the mesh
  27503. */
  27504. get: function () {
  27505. return Mesh._CAP_START;
  27506. },
  27507. enumerable: true,
  27508. configurable: true
  27509. });
  27510. Object.defineProperty(Mesh, "CAP_END", {
  27511. /**
  27512. * Mesh cap setting : one cap at the end of the mesh
  27513. */
  27514. get: function () {
  27515. return Mesh._CAP_END;
  27516. },
  27517. enumerable: true,
  27518. configurable: true
  27519. });
  27520. Object.defineProperty(Mesh, "CAP_ALL", {
  27521. /**
  27522. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27523. */
  27524. get: function () {
  27525. return Mesh._CAP_ALL;
  27526. },
  27527. enumerable: true,
  27528. configurable: true
  27529. });
  27530. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27531. set: function (callback) {
  27532. if (this._onBeforeDrawObserver) {
  27533. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27534. }
  27535. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27536. },
  27537. enumerable: true,
  27538. configurable: true
  27539. });
  27540. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27541. get: function () {
  27542. return this._morphTargetManager;
  27543. },
  27544. set: function (value) {
  27545. if (this._morphTargetManager === value) {
  27546. return;
  27547. }
  27548. this._morphTargetManager = value;
  27549. this._syncGeometryWithMorphTargetManager();
  27550. },
  27551. enumerable: true,
  27552. configurable: true
  27553. });
  27554. Object.defineProperty(Mesh.prototype, "source", {
  27555. get: function () {
  27556. return this._source;
  27557. },
  27558. enumerable: true,
  27559. configurable: true
  27560. });
  27561. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27562. get: function () {
  27563. return this._unIndexed;
  27564. },
  27565. set: function (value) {
  27566. if (this._unIndexed !== value) {
  27567. this._unIndexed = value;
  27568. this._markSubMeshesAsAttributesDirty();
  27569. }
  27570. },
  27571. enumerable: true,
  27572. configurable: true
  27573. });
  27574. // Methods
  27575. /**
  27576. * Returns the string "Mesh".
  27577. */
  27578. Mesh.prototype.getClassName = function () {
  27579. return "Mesh";
  27580. };
  27581. /**
  27582. * Returns a string.
  27583. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27584. */
  27585. Mesh.prototype.toString = function (fullDetails) {
  27586. var ret = _super.prototype.toString.call(this, fullDetails);
  27587. ret += ", n vertices: " + this.getTotalVertices();
  27588. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27589. if (this.animations) {
  27590. for (var i = 0; i < this.animations.length; i++) {
  27591. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27592. }
  27593. }
  27594. if (fullDetails) {
  27595. if (this._geometry) {
  27596. var ib = this.getIndices();
  27597. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27598. if (vb && ib) {
  27599. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27600. }
  27601. }
  27602. else {
  27603. ret += ", flat shading: UNKNOWN";
  27604. }
  27605. }
  27606. return ret;
  27607. };
  27608. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27609. /**
  27610. * True if the mesh has some Levels Of Details (LOD).
  27611. * Returns a boolean.
  27612. */
  27613. get: function () {
  27614. return this._LODLevels.length > 0;
  27615. },
  27616. enumerable: true,
  27617. configurable: true
  27618. });
  27619. /**
  27620. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27621. * @returns an array of {BABYLON.MeshLODLevel}
  27622. */
  27623. Mesh.prototype.getLODLevels = function () {
  27624. return this._LODLevels;
  27625. };
  27626. Mesh.prototype._sortLODLevels = function () {
  27627. this._LODLevels.sort(function (a, b) {
  27628. if (a.distance < b.distance) {
  27629. return 1;
  27630. }
  27631. if (a.distance > b.distance) {
  27632. return -1;
  27633. }
  27634. return 0;
  27635. });
  27636. };
  27637. /**
  27638. * Add a mesh as LOD level triggered at the given distance.
  27639. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27640. * @param {number} distance The distance from the center of the object to show this level
  27641. * @param {Mesh} mesh The mesh to be added as LOD level
  27642. * @return {Mesh} This mesh (for chaining)
  27643. */
  27644. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27645. if (mesh && mesh._masterMesh) {
  27646. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27647. return this;
  27648. }
  27649. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27650. this._LODLevels.push(level);
  27651. if (mesh) {
  27652. mesh._masterMesh = this;
  27653. }
  27654. this._sortLODLevels();
  27655. return this;
  27656. };
  27657. /**
  27658. * Returns the LOD level mesh at the passed distance or null if not found.
  27659. * It is related to the method `addLODLevel(distance, mesh)`.
  27660. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27661. * Returns an object Mesh or `null`.
  27662. */
  27663. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27664. for (var index = 0; index < this._LODLevels.length; index++) {
  27665. var level = this._LODLevels[index];
  27666. if (level.distance === distance) {
  27667. return level.mesh;
  27668. }
  27669. }
  27670. return null;
  27671. };
  27672. /**
  27673. * Remove a mesh from the LOD array
  27674. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27675. * @param {Mesh} mesh The mesh to be removed.
  27676. * @return {Mesh} This mesh (for chaining)
  27677. */
  27678. Mesh.prototype.removeLODLevel = function (mesh) {
  27679. for (var index = 0; index < this._LODLevels.length; index++) {
  27680. if (this._LODLevels[index].mesh === mesh) {
  27681. this._LODLevels.splice(index, 1);
  27682. if (mesh) {
  27683. mesh._masterMesh = null;
  27684. }
  27685. }
  27686. }
  27687. this._sortLODLevels();
  27688. return this;
  27689. };
  27690. /**
  27691. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27692. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27693. */
  27694. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27695. if (!this._LODLevels || this._LODLevels.length === 0) {
  27696. return this;
  27697. }
  27698. var bSphere;
  27699. if (boundingSphere) {
  27700. bSphere = boundingSphere;
  27701. }
  27702. else {
  27703. var boundingInfo = this.getBoundingInfo();
  27704. bSphere = boundingInfo.boundingSphere;
  27705. }
  27706. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27707. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27708. if (this.onLODLevelSelection) {
  27709. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27710. }
  27711. return this;
  27712. }
  27713. for (var index = 0; index < this._LODLevels.length; index++) {
  27714. var level = this._LODLevels[index];
  27715. if (level.distance < distanceToCamera) {
  27716. if (level.mesh) {
  27717. level.mesh._preActivate();
  27718. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27719. }
  27720. if (this.onLODLevelSelection) {
  27721. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27722. }
  27723. return level.mesh;
  27724. }
  27725. }
  27726. if (this.onLODLevelSelection) {
  27727. this.onLODLevelSelection(distanceToCamera, this, this);
  27728. }
  27729. return this;
  27730. };
  27731. Object.defineProperty(Mesh.prototype, "geometry", {
  27732. /**
  27733. * Returns the mesh internal Geometry object.
  27734. */
  27735. get: function () {
  27736. return this._geometry;
  27737. },
  27738. enumerable: true,
  27739. configurable: true
  27740. });
  27741. /**
  27742. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27743. */
  27744. Mesh.prototype.getTotalVertices = function () {
  27745. if (this._geometry === null || this._geometry === undefined) {
  27746. return 0;
  27747. }
  27748. return this._geometry.getTotalVertices();
  27749. };
  27750. /**
  27751. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27752. * 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.
  27753. * You can force the copy with forceCopy === true
  27754. * Returns null if the mesh has no geometry or no vertex buffer.
  27755. * Possible `kind` values :
  27756. * - BABYLON.VertexBuffer.PositionKind
  27757. * - BABYLON.VertexBuffer.UVKind
  27758. * - BABYLON.VertexBuffer.UV2Kind
  27759. * - BABYLON.VertexBuffer.UV3Kind
  27760. * - BABYLON.VertexBuffer.UV4Kind
  27761. * - BABYLON.VertexBuffer.UV5Kind
  27762. * - BABYLON.VertexBuffer.UV6Kind
  27763. * - BABYLON.VertexBuffer.ColorKind
  27764. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27765. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27766. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27767. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27768. */
  27769. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27770. if (!this._geometry) {
  27771. return null;
  27772. }
  27773. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27774. };
  27775. /**
  27776. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27777. * Returns `null` if the mesh has no geometry.
  27778. * Possible `kind` values :
  27779. * - BABYLON.VertexBuffer.PositionKind
  27780. * - BABYLON.VertexBuffer.UVKind
  27781. * - BABYLON.VertexBuffer.UV2Kind
  27782. * - BABYLON.VertexBuffer.UV3Kind
  27783. * - BABYLON.VertexBuffer.UV4Kind
  27784. * - BABYLON.VertexBuffer.UV5Kind
  27785. * - BABYLON.VertexBuffer.UV6Kind
  27786. * - BABYLON.VertexBuffer.ColorKind
  27787. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27788. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27789. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27790. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27791. */
  27792. Mesh.prototype.getVertexBuffer = function (kind) {
  27793. if (!this._geometry) {
  27794. return null;
  27795. }
  27796. return this._geometry.getVertexBuffer(kind);
  27797. };
  27798. /**
  27799. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27800. * Possible `kind` values :
  27801. * - BABYLON.VertexBuffer.PositionKind
  27802. * - BABYLON.VertexBuffer.UVKind
  27803. * - BABYLON.VertexBuffer.UV2Kind
  27804. * - BABYLON.VertexBuffer.UV3Kind
  27805. * - BABYLON.VertexBuffer.UV4Kind
  27806. * - BABYLON.VertexBuffer.UV5Kind
  27807. * - BABYLON.VertexBuffer.UV6Kind
  27808. * - BABYLON.VertexBuffer.ColorKind
  27809. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27810. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27811. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27812. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27813. */
  27814. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27815. if (!this._geometry) {
  27816. if (this._delayInfo) {
  27817. return this._delayInfo.indexOf(kind) !== -1;
  27818. }
  27819. return false;
  27820. }
  27821. return this._geometry.isVerticesDataPresent(kind);
  27822. };
  27823. /**
  27824. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27825. * Possible `kind` values :
  27826. * - BABYLON.VertexBuffer.PositionKind
  27827. * - BABYLON.VertexBuffer.UVKind
  27828. * - BABYLON.VertexBuffer.UV2Kind
  27829. * - BABYLON.VertexBuffer.UV3Kind
  27830. * - BABYLON.VertexBuffer.UV4Kind
  27831. * - BABYLON.VertexBuffer.UV5Kind
  27832. * - BABYLON.VertexBuffer.UV6Kind
  27833. * - BABYLON.VertexBuffer.ColorKind
  27834. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27835. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27836. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27837. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27838. */
  27839. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27840. if (!this._geometry) {
  27841. if (this._delayInfo) {
  27842. return this._delayInfo.indexOf(kind) !== -1;
  27843. }
  27844. return false;
  27845. }
  27846. return this._geometry.isVertexBufferUpdatable(kind);
  27847. };
  27848. /**
  27849. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27850. * Possible `kind` values :
  27851. * - BABYLON.VertexBuffer.PositionKind
  27852. * - BABYLON.VertexBuffer.UVKind
  27853. * - BABYLON.VertexBuffer.UV2Kind
  27854. * - BABYLON.VertexBuffer.UV3Kind
  27855. * - BABYLON.VertexBuffer.UV4Kind
  27856. * - BABYLON.VertexBuffer.UV5Kind
  27857. * - BABYLON.VertexBuffer.UV6Kind
  27858. * - BABYLON.VertexBuffer.ColorKind
  27859. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27860. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27861. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27862. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27863. */
  27864. Mesh.prototype.getVerticesDataKinds = function () {
  27865. if (!this._geometry) {
  27866. var result = new Array();
  27867. if (this._delayInfo) {
  27868. this._delayInfo.forEach(function (kind, index, array) {
  27869. result.push(kind);
  27870. });
  27871. }
  27872. return result;
  27873. }
  27874. return this._geometry.getVerticesDataKinds();
  27875. };
  27876. /**
  27877. * Returns a positive integer : the total number of indices in this mesh geometry.
  27878. * Returns zero if the mesh has no geometry.
  27879. */
  27880. Mesh.prototype.getTotalIndices = function () {
  27881. if (!this._geometry) {
  27882. return 0;
  27883. }
  27884. return this._geometry.getTotalIndices();
  27885. };
  27886. /**
  27887. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27888. * 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.
  27889. * Returns an empty array if the mesh has no geometry.
  27890. */
  27891. Mesh.prototype.getIndices = function (copyWhenShared) {
  27892. if (!this._geometry) {
  27893. return [];
  27894. }
  27895. return this._geometry.getIndices(copyWhenShared);
  27896. };
  27897. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27898. get: function () {
  27899. return this._masterMesh !== null && this._masterMesh !== undefined;
  27900. },
  27901. enumerable: true,
  27902. configurable: true
  27903. });
  27904. /**
  27905. * Determine if the current mesh is ready to be rendered
  27906. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27907. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27908. * @returns true if all associated assets are ready (material, textures, shaders)
  27909. */
  27910. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27911. if (completeCheck === void 0) { completeCheck = false; }
  27912. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27913. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27914. return false;
  27915. }
  27916. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27917. return false;
  27918. }
  27919. if (!this.subMeshes || this.subMeshes.length === 0) {
  27920. return true;
  27921. }
  27922. if (!completeCheck) {
  27923. return true;
  27924. }
  27925. var engine = this.getEngine();
  27926. var scene = this.getScene();
  27927. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27928. this.computeWorldMatrix();
  27929. var mat = this.material || scene.defaultMaterial;
  27930. if (mat) {
  27931. if (mat.storeEffectOnSubMeshes) {
  27932. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27933. var subMesh = _a[_i];
  27934. var effectiveMaterial = subMesh.getMaterial();
  27935. if (effectiveMaterial) {
  27936. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27937. return false;
  27938. }
  27939. }
  27940. }
  27941. }
  27942. else {
  27943. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27944. return false;
  27945. }
  27946. }
  27947. }
  27948. // Shadows
  27949. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27950. var light = _c[_b];
  27951. var generator = light.getShadowGenerator();
  27952. if (generator) {
  27953. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27954. var subMesh = _e[_d];
  27955. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27956. return false;
  27957. }
  27958. }
  27959. }
  27960. }
  27961. // LOD
  27962. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27963. var lod = _g[_f];
  27964. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27965. return false;
  27966. }
  27967. }
  27968. return true;
  27969. };
  27970. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27971. /**
  27972. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27973. * This property is pertinent only for updatable parametric shapes.
  27974. */
  27975. get: function () {
  27976. return this._areNormalsFrozen;
  27977. },
  27978. enumerable: true,
  27979. configurable: true
  27980. });
  27981. /**
  27982. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27983. * It has no effect at all on other shapes.
  27984. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27985. * Returns the Mesh.
  27986. */
  27987. Mesh.prototype.freezeNormals = function () {
  27988. this._areNormalsFrozen = true;
  27989. return this;
  27990. };
  27991. /**
  27992. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27993. * It has no effect at all on other shapes.
  27994. * It reactivates the mesh normals computation if it was previously frozen.
  27995. * Returns the Mesh.
  27996. */
  27997. Mesh.prototype.unfreezeNormals = function () {
  27998. this._areNormalsFrozen = false;
  27999. return this;
  28000. };
  28001. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28002. /**
  28003. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28004. */
  28005. set: function (count) {
  28006. this._overridenInstanceCount = count;
  28007. },
  28008. enumerable: true,
  28009. configurable: true
  28010. });
  28011. // Methods
  28012. Mesh.prototype._preActivate = function () {
  28013. var sceneRenderId = this.getScene().getRenderId();
  28014. if (this._preActivateId === sceneRenderId) {
  28015. return this;
  28016. }
  28017. this._preActivateId = sceneRenderId;
  28018. this._visibleInstances = null;
  28019. return this;
  28020. };
  28021. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28022. if (this._visibleInstances) {
  28023. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28024. }
  28025. return this;
  28026. };
  28027. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28028. if (!this._visibleInstances) {
  28029. this._visibleInstances = {};
  28030. this._visibleInstances.defaultRenderId = renderId;
  28031. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28032. }
  28033. if (!this._visibleInstances[renderId]) {
  28034. this._visibleInstances[renderId] = new Array();
  28035. }
  28036. this._visibleInstances[renderId].push(instance);
  28037. return this;
  28038. };
  28039. /**
  28040. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28041. * This means the mesh underlying bounding box and sphere are recomputed.
  28042. * Returns the Mesh.
  28043. */
  28044. Mesh.prototype.refreshBoundingInfo = function () {
  28045. return this._refreshBoundingInfo(false);
  28046. };
  28047. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28048. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28049. return this;
  28050. }
  28051. var data = this._getPositionData(applySkeleton);
  28052. if (data) {
  28053. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28054. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28055. }
  28056. if (this.subMeshes) {
  28057. for (var index = 0; index < this.subMeshes.length; index++) {
  28058. this.subMeshes[index].refreshBoundingInfo();
  28059. }
  28060. }
  28061. this._updateBoundingInfo();
  28062. return this;
  28063. };
  28064. Mesh.prototype._getPositionData = function (applySkeleton) {
  28065. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28066. if (data && applySkeleton && this.skeleton) {
  28067. data = BABYLON.Tools.Slice(data);
  28068. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28069. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28070. if (matricesWeightsData && matricesIndicesData) {
  28071. var needExtras = this.numBoneInfluencers > 4;
  28072. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28073. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28074. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28075. var tempVector = BABYLON.Tmp.Vector3[0];
  28076. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28077. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28078. var matWeightIdx = 0;
  28079. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28080. finalMatrix.reset();
  28081. var inf;
  28082. var weight;
  28083. for (inf = 0; inf < 4; inf++) {
  28084. weight = matricesWeightsData[matWeightIdx + inf];
  28085. if (weight <= 0)
  28086. break;
  28087. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28088. finalMatrix.addToSelf(tempMatrix);
  28089. }
  28090. if (needExtras) {
  28091. for (inf = 0; inf < 4; inf++) {
  28092. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28093. if (weight <= 0)
  28094. break;
  28095. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28096. finalMatrix.addToSelf(tempMatrix);
  28097. }
  28098. }
  28099. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28100. tempVector.toArray(data, index);
  28101. }
  28102. }
  28103. }
  28104. return data;
  28105. };
  28106. Mesh.prototype._createGlobalSubMesh = function (force) {
  28107. var totalVertices = this.getTotalVertices();
  28108. if (!totalVertices || !this.getIndices()) {
  28109. return null;
  28110. }
  28111. // Check if we need to recreate the submeshes
  28112. if (this.subMeshes && this.subMeshes.length > 0) {
  28113. var ib = this.getIndices();
  28114. if (!ib) {
  28115. return null;
  28116. }
  28117. var totalIndices = ib.length;
  28118. var needToRecreate = false;
  28119. if (force) {
  28120. needToRecreate = true;
  28121. }
  28122. else {
  28123. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28124. var submesh = _a[_i];
  28125. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28126. needToRecreate = true;
  28127. break;
  28128. }
  28129. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28130. needToRecreate = true;
  28131. break;
  28132. }
  28133. }
  28134. }
  28135. if (!needToRecreate) {
  28136. return this.subMeshes[0];
  28137. }
  28138. }
  28139. this.releaseSubMeshes();
  28140. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28141. };
  28142. Mesh.prototype.subdivide = function (count) {
  28143. if (count < 1) {
  28144. return;
  28145. }
  28146. var totalIndices = this.getTotalIndices();
  28147. var subdivisionSize = (totalIndices / count) | 0;
  28148. var offset = 0;
  28149. // Ensure that subdivisionSize is a multiple of 3
  28150. while (subdivisionSize % 3 !== 0) {
  28151. subdivisionSize++;
  28152. }
  28153. this.releaseSubMeshes();
  28154. for (var index = 0; index < count; index++) {
  28155. if (offset >= totalIndices) {
  28156. break;
  28157. }
  28158. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28159. offset += subdivisionSize;
  28160. }
  28161. this.synchronizeInstances();
  28162. };
  28163. /**
  28164. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28165. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28166. * The `data` are either a numeric array either a Float32Array.
  28167. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28168. * 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).
  28169. * Note that a new underlying VertexBuffer object is created each call.
  28170. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28171. *
  28172. * Possible `kind` values :
  28173. * - BABYLON.VertexBuffer.PositionKind
  28174. * - BABYLON.VertexBuffer.UVKind
  28175. * - BABYLON.VertexBuffer.UV2Kind
  28176. * - BABYLON.VertexBuffer.UV3Kind
  28177. * - BABYLON.VertexBuffer.UV4Kind
  28178. * - BABYLON.VertexBuffer.UV5Kind
  28179. * - BABYLON.VertexBuffer.UV6Kind
  28180. * - BABYLON.VertexBuffer.ColorKind
  28181. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28182. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28183. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28184. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28185. *
  28186. * Returns the Mesh.
  28187. */
  28188. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28189. if (updatable === void 0) { updatable = false; }
  28190. if (!this._geometry) {
  28191. var vertexData = new BABYLON.VertexData();
  28192. vertexData.set(data, kind);
  28193. var scene = this.getScene();
  28194. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28195. }
  28196. else {
  28197. this._geometry.setVerticesData(kind, data, updatable, stride);
  28198. }
  28199. return this;
  28200. };
  28201. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28202. if (updatable === void 0) { updatable = true; }
  28203. var vb = this.getVertexBuffer(kind);
  28204. if (!vb || vb.isUpdatable() === updatable) {
  28205. return;
  28206. }
  28207. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28208. };
  28209. /**
  28210. * Sets the mesh VertexBuffer.
  28211. * Returns the Mesh.
  28212. */
  28213. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28214. if (!this._geometry) {
  28215. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28216. }
  28217. this._geometry.setVerticesBuffer(buffer);
  28218. return this;
  28219. };
  28220. /**
  28221. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28222. * If the mesh has no geometry, it is simply returned as it is.
  28223. * The `data` are either a numeric array either a Float32Array.
  28224. * No new underlying VertexBuffer object is created.
  28225. * 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.
  28226. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28227. *
  28228. * Possible `kind` values :
  28229. * - BABYLON.VertexBuffer.PositionKind
  28230. * - BABYLON.VertexBuffer.UVKind
  28231. * - BABYLON.VertexBuffer.UV2Kind
  28232. * - BABYLON.VertexBuffer.UV3Kind
  28233. * - BABYLON.VertexBuffer.UV4Kind
  28234. * - BABYLON.VertexBuffer.UV5Kind
  28235. * - BABYLON.VertexBuffer.UV6Kind
  28236. * - BABYLON.VertexBuffer.ColorKind
  28237. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28238. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28239. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28240. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28241. *
  28242. * Returns the Mesh.
  28243. */
  28244. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28245. if (!this._geometry) {
  28246. return this;
  28247. }
  28248. if (!makeItUnique) {
  28249. this._geometry.updateVerticesData(kind, data, updateExtends);
  28250. }
  28251. else {
  28252. this.makeGeometryUnique();
  28253. this.updateVerticesData(kind, data, updateExtends, false);
  28254. }
  28255. return this;
  28256. };
  28257. /**
  28258. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28259. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28260. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28261. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28262. * Returns the Mesh.
  28263. */
  28264. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28265. if (computeNormals === void 0) { computeNormals = true; }
  28266. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28267. if (!positions) {
  28268. return this;
  28269. }
  28270. positionFunction(positions);
  28271. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28272. if (computeNormals) {
  28273. var indices = this.getIndices();
  28274. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28275. if (!normals) {
  28276. return this;
  28277. }
  28278. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28279. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28280. }
  28281. return this;
  28282. };
  28283. /**
  28284. * Creates a un-shared specific occurence of the geometry for the mesh.
  28285. * Returns the Mesh.
  28286. */
  28287. Mesh.prototype.makeGeometryUnique = function () {
  28288. if (!this._geometry) {
  28289. return this;
  28290. }
  28291. var oldGeometry = this._geometry;
  28292. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28293. oldGeometry.releaseForMesh(this, true);
  28294. geometry.applyToMesh(this);
  28295. return this;
  28296. };
  28297. /**
  28298. * Sets the mesh indices.
  28299. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28300. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28301. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28302. * This method creates a new index buffer each call.
  28303. * Returns the Mesh.
  28304. */
  28305. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28306. if (totalVertices === void 0) { totalVertices = null; }
  28307. if (updatable === void 0) { updatable = false; }
  28308. if (!this._geometry) {
  28309. var vertexData = new BABYLON.VertexData();
  28310. vertexData.indices = indices;
  28311. var scene = this.getScene();
  28312. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28313. }
  28314. else {
  28315. this._geometry.setIndices(indices, totalVertices, updatable);
  28316. }
  28317. return this;
  28318. };
  28319. /**
  28320. * Update the current index buffer
  28321. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28322. * Returns the Mesh.
  28323. */
  28324. Mesh.prototype.updateIndices = function (indices, offset) {
  28325. if (!this._geometry) {
  28326. return this;
  28327. }
  28328. this._geometry.updateIndices(indices, offset);
  28329. return this;
  28330. };
  28331. /**
  28332. * Invert the geometry to move from a right handed system to a left handed one.
  28333. * Returns the Mesh.
  28334. */
  28335. Mesh.prototype.toLeftHanded = function () {
  28336. if (!this._geometry) {
  28337. return this;
  28338. }
  28339. this._geometry.toLeftHanded();
  28340. return this;
  28341. };
  28342. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28343. if (!this._geometry) {
  28344. return this;
  28345. }
  28346. var engine = this.getScene().getEngine();
  28347. // Wireframe
  28348. var indexToBind;
  28349. if (this._unIndexed) {
  28350. indexToBind = null;
  28351. }
  28352. else {
  28353. switch (fillMode) {
  28354. case BABYLON.Material.PointFillMode:
  28355. indexToBind = null;
  28356. break;
  28357. case BABYLON.Material.WireFrameFillMode:
  28358. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28359. break;
  28360. default:
  28361. case BABYLON.Material.TriangleFillMode:
  28362. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28363. break;
  28364. }
  28365. }
  28366. // VBOs
  28367. this._geometry._bind(effect, indexToBind);
  28368. return this;
  28369. };
  28370. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28371. if (alternate === void 0) { alternate = false; }
  28372. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28373. return this;
  28374. }
  28375. this.onBeforeDrawObservable.notifyObservers(this);
  28376. var scene = this.getScene();
  28377. var engine = scene.getEngine();
  28378. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28379. // or triangles as points
  28380. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28381. }
  28382. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28383. // Triangles as wireframe
  28384. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28385. }
  28386. else {
  28387. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28388. }
  28389. if (scene._isAlternateRenderingEnabled && !alternate) {
  28390. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28391. if (!effect || !scene.activeCamera) {
  28392. return this;
  28393. }
  28394. scene._switchToAlternateCameraConfiguration(true);
  28395. this._effectiveMaterial.bindView(effect);
  28396. this._effectiveMaterial.bindViewProjection(effect);
  28397. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28398. this._draw(subMesh, fillMode, instancesCount, true);
  28399. engine.setViewport(scene.activeCamera.viewport);
  28400. scene._switchToAlternateCameraConfiguration(false);
  28401. this._effectiveMaterial.bindView(effect);
  28402. this._effectiveMaterial.bindViewProjection(effect);
  28403. }
  28404. return this;
  28405. };
  28406. /**
  28407. * Registers for this mesh a javascript function called just before the rendering process.
  28408. * This function is passed the current mesh.
  28409. * Return the Mesh.
  28410. */
  28411. Mesh.prototype.registerBeforeRender = function (func) {
  28412. this.onBeforeRenderObservable.add(func);
  28413. return this;
  28414. };
  28415. /**
  28416. * Disposes a previously registered javascript function called before the rendering.
  28417. * This function is passed the current mesh.
  28418. * Returns the Mesh.
  28419. */
  28420. Mesh.prototype.unregisterBeforeRender = function (func) {
  28421. this.onBeforeRenderObservable.removeCallback(func);
  28422. return this;
  28423. };
  28424. /**
  28425. * Registers for this mesh a javascript function called just after the rendering is complete.
  28426. * This function is passed the current mesh.
  28427. * Returns the Mesh.
  28428. */
  28429. Mesh.prototype.registerAfterRender = function (func) {
  28430. this.onAfterRenderObservable.add(func);
  28431. return this;
  28432. };
  28433. /**
  28434. * Disposes a previously registered javascript function called after the rendering.
  28435. * This function is passed the current mesh.
  28436. * Return the Mesh.
  28437. */
  28438. Mesh.prototype.unregisterAfterRender = function (func) {
  28439. this.onAfterRenderObservable.removeCallback(func);
  28440. return this;
  28441. };
  28442. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28443. var scene = this.getScene();
  28444. this._batchCache.mustReturn = false;
  28445. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28446. this._batchCache.visibleInstances[subMeshId] = null;
  28447. if (this._visibleInstances) {
  28448. var currentRenderId = scene.getRenderId();
  28449. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28450. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28451. var selfRenderId = this._renderId;
  28452. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28453. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28454. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28455. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28456. }
  28457. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28458. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28459. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28460. this._batchCache.mustReturn = true;
  28461. return this._batchCache;
  28462. }
  28463. if (currentRenderId !== selfRenderId) {
  28464. this._batchCache.renderSelf[subMeshId] = false;
  28465. }
  28466. }
  28467. this._renderIdForInstances[subMeshId] = currentRenderId;
  28468. }
  28469. return this._batchCache;
  28470. };
  28471. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28472. var visibleInstances = batch.visibleInstances[subMesh._id];
  28473. if (!visibleInstances) {
  28474. return this;
  28475. }
  28476. var matricesCount = visibleInstances.length + 1;
  28477. var bufferSize = matricesCount * 16 * 4;
  28478. var currentInstancesBufferSize = this._instancesBufferSize;
  28479. var instancesBuffer = this._instancesBuffer;
  28480. while (this._instancesBufferSize < bufferSize) {
  28481. this._instancesBufferSize *= 2;
  28482. }
  28483. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28484. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28485. }
  28486. var offset = 0;
  28487. var instancesCount = 0;
  28488. var world = this.getWorldMatrix();
  28489. if (batch.renderSelf[subMesh._id]) {
  28490. world.copyToArray(this._instancesData, offset);
  28491. offset += 16;
  28492. instancesCount++;
  28493. }
  28494. if (visibleInstances) {
  28495. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28496. var instance = visibleInstances[instanceIndex];
  28497. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28498. offset += 16;
  28499. instancesCount++;
  28500. }
  28501. }
  28502. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28503. if (instancesBuffer) {
  28504. instancesBuffer.dispose();
  28505. }
  28506. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28507. this._instancesBuffer = instancesBuffer;
  28508. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28509. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28510. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28511. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28512. }
  28513. else {
  28514. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28515. }
  28516. this._bind(subMesh, effect, fillMode);
  28517. this._draw(subMesh, fillMode, instancesCount);
  28518. engine.unbindInstanceAttributes();
  28519. return this;
  28520. };
  28521. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28522. var scene = this.getScene();
  28523. var engine = scene.getEngine();
  28524. if (hardwareInstancedRendering) {
  28525. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28526. }
  28527. else {
  28528. if (batch.renderSelf[subMesh._id]) {
  28529. // Draw
  28530. if (onBeforeDraw) {
  28531. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28532. }
  28533. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28534. }
  28535. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28536. if (visibleInstancesForSubMesh) {
  28537. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28538. var instance = visibleInstancesForSubMesh[instanceIndex];
  28539. // World
  28540. var world = instance.getWorldMatrix();
  28541. if (onBeforeDraw) {
  28542. onBeforeDraw(true, world, effectiveMaterial);
  28543. }
  28544. // Draw
  28545. this._draw(subMesh, fillMode);
  28546. }
  28547. }
  28548. }
  28549. return this;
  28550. };
  28551. /**
  28552. * Triggers the draw call for the mesh.
  28553. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28554. * Returns the Mesh.
  28555. */
  28556. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28557. this.checkOcclusionQuery();
  28558. if (this._isOccluded) {
  28559. return this;
  28560. }
  28561. var scene = this.getScene();
  28562. // Managing instances
  28563. var batch = this._getInstancesRenderList(subMesh._id);
  28564. if (batch.mustReturn) {
  28565. return this;
  28566. }
  28567. // Checking geometry state
  28568. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28569. return this;
  28570. }
  28571. this.onBeforeRenderObservable.notifyObservers(this);
  28572. var engine = scene.getEngine();
  28573. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28574. // Material
  28575. var material = subMesh.getMaterial();
  28576. if (!material) {
  28577. return this;
  28578. }
  28579. this._effectiveMaterial = material;
  28580. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28581. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28582. return this;
  28583. }
  28584. }
  28585. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28586. return this;
  28587. }
  28588. // Alpha mode
  28589. if (enableAlphaMode) {
  28590. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28591. }
  28592. // Outline - step 1
  28593. var savedDepthWrite = engine.getDepthWrite();
  28594. if (this.renderOutline) {
  28595. engine.setDepthWrite(false);
  28596. scene.getOutlineRenderer().render(subMesh, batch);
  28597. engine.setDepthWrite(savedDepthWrite);
  28598. }
  28599. var effect;
  28600. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28601. effect = subMesh.effect;
  28602. }
  28603. else {
  28604. effect = this._effectiveMaterial.getEffect();
  28605. }
  28606. if (!effect) {
  28607. return this;
  28608. }
  28609. var sideOrientation = this.overrideMaterialSideOrientation;
  28610. if (sideOrientation == null) {
  28611. sideOrientation = this._effectiveMaterial.sideOrientation;
  28612. if (this._getWorldMatrixDeterminant() < 0) {
  28613. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28614. }
  28615. }
  28616. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28617. if (this._effectiveMaterial.forceDepthWrite) {
  28618. engine.setDepthWrite(true);
  28619. }
  28620. // Bind
  28621. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28622. if (!hardwareInstancedRendering) {
  28623. this._bind(subMesh, effect, fillMode);
  28624. }
  28625. var world = this.getWorldMatrix();
  28626. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28627. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28628. }
  28629. else {
  28630. this._effectiveMaterial.bind(world, this);
  28631. }
  28632. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28633. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28634. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28635. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28636. }
  28637. // Draw
  28638. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28639. // Unbind
  28640. this._effectiveMaterial.unbind();
  28641. // Outline - step 2
  28642. if (this.renderOutline && savedDepthWrite) {
  28643. engine.setDepthWrite(true);
  28644. engine.setColorWrite(false);
  28645. scene.getOutlineRenderer().render(subMesh, batch);
  28646. engine.setColorWrite(true);
  28647. }
  28648. // Overlay
  28649. if (this.renderOverlay) {
  28650. var currentMode = engine.getAlphaMode();
  28651. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28652. scene.getOutlineRenderer().render(subMesh, batch, true);
  28653. engine.setAlphaMode(currentMode);
  28654. }
  28655. this.onAfterRenderObservable.notifyObservers(this);
  28656. return this;
  28657. };
  28658. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28659. if (isInstance && effectiveMaterial) {
  28660. effectiveMaterial.bindOnlyWorldMatrix(world);
  28661. }
  28662. };
  28663. /**
  28664. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28665. */
  28666. Mesh.prototype.getEmittedParticleSystems = function () {
  28667. var results = new Array();
  28668. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28669. var particleSystem = this.getScene().particleSystems[index];
  28670. if (particleSystem.emitter === this) {
  28671. results.push(particleSystem);
  28672. }
  28673. }
  28674. return results;
  28675. };
  28676. /**
  28677. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28678. */
  28679. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28680. var results = new Array();
  28681. var descendants = this.getDescendants();
  28682. descendants.push(this);
  28683. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28684. var particleSystem = this.getScene().particleSystems[index];
  28685. var emitter = particleSystem.emitter;
  28686. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28687. results.push(particleSystem);
  28688. }
  28689. }
  28690. return results;
  28691. };
  28692. Mesh.prototype._checkDelayState = function () {
  28693. var scene = this.getScene();
  28694. if (this._geometry) {
  28695. this._geometry.load(scene);
  28696. }
  28697. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28698. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28699. this._queueLoad(scene);
  28700. }
  28701. return this;
  28702. };
  28703. Mesh.prototype._queueLoad = function (scene) {
  28704. var _this = this;
  28705. scene._addPendingData(this);
  28706. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28707. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28708. if (data instanceof ArrayBuffer) {
  28709. _this._delayLoadingFunction(data, _this);
  28710. }
  28711. else {
  28712. _this._delayLoadingFunction(JSON.parse(data), _this);
  28713. }
  28714. _this.instances.forEach(function (instance) {
  28715. instance._syncSubMeshes();
  28716. });
  28717. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28718. scene._removePendingData(_this);
  28719. }, function () { }, scene.database, getBinaryData);
  28720. return this;
  28721. };
  28722. /**
  28723. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28724. */
  28725. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28726. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28727. return false;
  28728. }
  28729. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28730. return false;
  28731. }
  28732. this._checkDelayState();
  28733. return true;
  28734. };
  28735. /**
  28736. * Sets the mesh material by the material or multiMaterial `id` property.
  28737. * The material `id` is a string identifying the material or the multiMaterial.
  28738. * This method returns the Mesh.
  28739. */
  28740. Mesh.prototype.setMaterialByID = function (id) {
  28741. var materials = this.getScene().materials;
  28742. var index;
  28743. for (index = materials.length - 1; index > -1; index--) {
  28744. if (materials[index].id === id) {
  28745. this.material = materials[index];
  28746. return this;
  28747. }
  28748. }
  28749. // Multi
  28750. var multiMaterials = this.getScene().multiMaterials;
  28751. for (index = multiMaterials.length - 1; index > -1; index--) {
  28752. if (multiMaterials[index].id === id) {
  28753. this.material = multiMaterials[index];
  28754. return this;
  28755. }
  28756. }
  28757. return this;
  28758. };
  28759. /**
  28760. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28761. */
  28762. Mesh.prototype.getAnimatables = function () {
  28763. var results = new Array();
  28764. if (this.material) {
  28765. results.push(this.material);
  28766. }
  28767. if (this.skeleton) {
  28768. results.push(this.skeleton);
  28769. }
  28770. return results;
  28771. };
  28772. /**
  28773. * Modifies the mesh geometry according to the passed transformation matrix.
  28774. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28775. * The mesh normals are modified accordingly the same transformation.
  28776. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28777. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28778. * Returns the Mesh.
  28779. */
  28780. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28781. // Position
  28782. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28783. return this;
  28784. }
  28785. var submeshes = this.subMeshes.splice(0);
  28786. this._resetPointsArrayCache();
  28787. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28788. var temp = new Array();
  28789. var index;
  28790. for (index = 0; index < data.length; index += 3) {
  28791. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28792. }
  28793. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28794. // Normals
  28795. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28796. return this;
  28797. }
  28798. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28799. temp = [];
  28800. for (index = 0; index < data.length; index += 3) {
  28801. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28802. }
  28803. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28804. // flip faces?
  28805. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28806. this.flipFaces();
  28807. }
  28808. // Restore submeshes
  28809. this.releaseSubMeshes();
  28810. this.subMeshes = submeshes;
  28811. return this;
  28812. };
  28813. /**
  28814. * Modifies the mesh geometry according to its own current World Matrix.
  28815. * The mesh World Matrix is then reset.
  28816. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28817. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28818. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28819. * Returns the Mesh.
  28820. */
  28821. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28822. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28823. this.scaling.copyFromFloats(1, 1, 1);
  28824. this.position.copyFromFloats(0, 0, 0);
  28825. this.rotation.copyFromFloats(0, 0, 0);
  28826. //only if quaternion is already set
  28827. if (this.rotationQuaternion) {
  28828. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28829. }
  28830. this._worldMatrix = BABYLON.Matrix.Identity();
  28831. return this;
  28832. };
  28833. Object.defineProperty(Mesh.prototype, "_positions", {
  28834. // Cache
  28835. get: function () {
  28836. if (this._geometry) {
  28837. return this._geometry._positions;
  28838. }
  28839. return null;
  28840. },
  28841. enumerable: true,
  28842. configurable: true
  28843. });
  28844. Mesh.prototype._resetPointsArrayCache = function () {
  28845. if (this._geometry) {
  28846. this._geometry._resetPointsArrayCache();
  28847. }
  28848. return this;
  28849. };
  28850. Mesh.prototype._generatePointsArray = function () {
  28851. if (this._geometry) {
  28852. return this._geometry._generatePointsArray();
  28853. }
  28854. return false;
  28855. };
  28856. /**
  28857. * Returns a new Mesh object generated from the current mesh properties.
  28858. * This method must not get confused with createInstance().
  28859. * The parameter `name` is a string, the name given to the new mesh.
  28860. * The optional parameter `newParent` can be any Node object (default `null`).
  28861. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28862. * 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.
  28863. */
  28864. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28865. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28866. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28867. };
  28868. /**
  28869. * Releases resources associated with this mesh.
  28870. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  28871. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  28872. */
  28873. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28874. var _this = this;
  28875. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28876. this.morphTargetManager = null;
  28877. if (this._geometry) {
  28878. this._geometry.releaseForMesh(this, true);
  28879. }
  28880. // Sources
  28881. var meshes = this.getScene().meshes;
  28882. meshes.forEach(function (abstractMesh) {
  28883. var mesh = abstractMesh;
  28884. if (mesh._source && mesh._source === _this) {
  28885. mesh._source = null;
  28886. }
  28887. });
  28888. this._source = null;
  28889. // Instances
  28890. if (this._instancesBuffer) {
  28891. this._instancesBuffer.dispose();
  28892. this._instancesBuffer = null;
  28893. }
  28894. while (this.instances.length) {
  28895. this.instances[0].dispose();
  28896. }
  28897. // Effect layers.
  28898. var effectLayers = this.getScene().effectLayers;
  28899. for (var i = 0; i < effectLayers.length; i++) {
  28900. var effectLayer = effectLayers[i];
  28901. if (effectLayer) {
  28902. effectLayer._disposeMesh(this);
  28903. }
  28904. }
  28905. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28906. };
  28907. /**
  28908. * Modifies the mesh geometry according to a displacement map.
  28909. * 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.
  28910. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28911. * This method returns nothing.
  28912. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28913. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28914. * 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.
  28915. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28916. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28917. *
  28918. * Returns the Mesh.
  28919. */
  28920. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28921. var _this = this;
  28922. var scene = this.getScene();
  28923. var onload = function (img) {
  28924. // Getting height map data
  28925. var canvas = document.createElement("canvas");
  28926. var context = canvas.getContext("2d");
  28927. var heightMapWidth = img.width;
  28928. var heightMapHeight = img.height;
  28929. canvas.width = heightMapWidth;
  28930. canvas.height = heightMapHeight;
  28931. context.drawImage(img, 0, 0);
  28932. // Create VertexData from map data
  28933. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28934. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28935. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28936. //execute success callback, if set
  28937. if (onSuccess) {
  28938. onSuccess(_this);
  28939. }
  28940. };
  28941. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28942. return this;
  28943. };
  28944. /**
  28945. * Modifies the mesh geometry according to a displacementMap buffer.
  28946. * 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.
  28947. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28948. * This method returns nothing.
  28949. * 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.
  28950. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28951. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28952. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28953. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28954. *
  28955. * Returns the Mesh.
  28956. */
  28957. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28958. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28959. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28960. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28961. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28962. return this;
  28963. }
  28964. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28965. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28966. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28967. var position = BABYLON.Vector3.Zero();
  28968. var normal = BABYLON.Vector3.Zero();
  28969. var uv = BABYLON.Vector2.Zero();
  28970. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28971. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28972. for (var index = 0; index < positions.length; index += 3) {
  28973. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28974. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28975. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28976. // Compute height
  28977. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28978. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28979. var pos = (u + v * heightMapWidth) * 4;
  28980. var r = buffer[pos] / 255.0;
  28981. var g = buffer[pos + 1] / 255.0;
  28982. var b = buffer[pos + 2] / 255.0;
  28983. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28984. normal.normalize();
  28985. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28986. position = position.add(normal);
  28987. position.toArray(positions, index);
  28988. }
  28989. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28990. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28991. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28992. return this;
  28993. };
  28994. /**
  28995. * Modify the mesh to get a flat shading rendering.
  28996. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28997. * This method returns the Mesh.
  28998. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28999. */
  29000. Mesh.prototype.convertToFlatShadedMesh = function () {
  29001. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29002. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29003. var kinds = this.getVerticesDataKinds();
  29004. var vbs = {};
  29005. var data = {};
  29006. var newdata = {};
  29007. var updatableNormals = false;
  29008. var kindIndex;
  29009. var kind;
  29010. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29011. kind = kinds[kindIndex];
  29012. var vertexBuffer = this.getVertexBuffer(kind);
  29013. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29014. updatableNormals = vertexBuffer.isUpdatable();
  29015. kinds.splice(kindIndex, 1);
  29016. kindIndex--;
  29017. continue;
  29018. }
  29019. vbs[kind] = vertexBuffer;
  29020. data[kind] = vbs[kind].getData();
  29021. newdata[kind] = [];
  29022. }
  29023. // Save previous submeshes
  29024. var previousSubmeshes = this.subMeshes.slice(0);
  29025. var indices = this.getIndices();
  29026. var totalIndices = this.getTotalIndices();
  29027. // Generating unique vertices per face
  29028. var index;
  29029. for (index = 0; index < totalIndices; index++) {
  29030. var vertexIndex = indices[index];
  29031. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29032. kind = kinds[kindIndex];
  29033. var stride = vbs[kind].getStrideSize();
  29034. for (var offset = 0; offset < stride; offset++) {
  29035. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29036. }
  29037. }
  29038. }
  29039. // Updating faces & normal
  29040. var normals = [];
  29041. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29042. for (index = 0; index < totalIndices; index += 3) {
  29043. indices[index] = index;
  29044. indices[index + 1] = index + 1;
  29045. indices[index + 2] = index + 2;
  29046. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29047. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29048. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29049. var p1p2 = p1.subtract(p2);
  29050. var p3p2 = p3.subtract(p2);
  29051. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29052. // Store same normals for every vertex
  29053. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29054. normals.push(normal.x);
  29055. normals.push(normal.y);
  29056. normals.push(normal.z);
  29057. }
  29058. }
  29059. this.setIndices(indices);
  29060. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29061. // Updating vertex buffers
  29062. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29063. kind = kinds[kindIndex];
  29064. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29065. }
  29066. // Updating submeshes
  29067. this.releaseSubMeshes();
  29068. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29069. var previousOne = previousSubmeshes[submeshIndex];
  29070. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29071. }
  29072. this.synchronizeInstances();
  29073. return this;
  29074. };
  29075. /**
  29076. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29077. * In other words, more vertices, no more indices and a single bigger VBO.
  29078. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29079. * Returns the Mesh.
  29080. */
  29081. Mesh.prototype.convertToUnIndexedMesh = function () {
  29082. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29083. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29084. var kinds = this.getVerticesDataKinds();
  29085. var vbs = {};
  29086. var data = {};
  29087. var newdata = {};
  29088. var kindIndex;
  29089. var kind;
  29090. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29091. kind = kinds[kindIndex];
  29092. var vertexBuffer = this.getVertexBuffer(kind);
  29093. vbs[kind] = vertexBuffer;
  29094. data[kind] = vbs[kind].getData();
  29095. newdata[kind] = [];
  29096. }
  29097. // Save previous submeshes
  29098. var previousSubmeshes = this.subMeshes.slice(0);
  29099. var indices = this.getIndices();
  29100. var totalIndices = this.getTotalIndices();
  29101. // Generating unique vertices per face
  29102. var index;
  29103. for (index = 0; index < totalIndices; index++) {
  29104. var vertexIndex = indices[index];
  29105. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29106. kind = kinds[kindIndex];
  29107. var stride = vbs[kind].getStrideSize();
  29108. for (var offset = 0; offset < stride; offset++) {
  29109. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29110. }
  29111. }
  29112. }
  29113. // Updating indices
  29114. for (index = 0; index < totalIndices; index += 3) {
  29115. indices[index] = index;
  29116. indices[index + 1] = index + 1;
  29117. indices[index + 2] = index + 2;
  29118. }
  29119. this.setIndices(indices);
  29120. // Updating vertex buffers
  29121. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29122. kind = kinds[kindIndex];
  29123. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29124. }
  29125. // Updating submeshes
  29126. this.releaseSubMeshes();
  29127. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29128. var previousOne = previousSubmeshes[submeshIndex];
  29129. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29130. }
  29131. this._unIndexed = true;
  29132. this.synchronizeInstances();
  29133. return this;
  29134. };
  29135. /**
  29136. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29137. * This method returns the Mesh.
  29138. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29139. */
  29140. Mesh.prototype.flipFaces = function (flipNormals) {
  29141. if (flipNormals === void 0) { flipNormals = false; }
  29142. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29143. var i;
  29144. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29145. for (i = 0; i < vertex_data.normals.length; i++) {
  29146. vertex_data.normals[i] *= -1;
  29147. }
  29148. }
  29149. if (vertex_data.indices) {
  29150. var temp;
  29151. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29152. // reassign indices
  29153. temp = vertex_data.indices[i + 1];
  29154. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29155. vertex_data.indices[i + 2] = temp;
  29156. }
  29157. }
  29158. vertex_data.applyToMesh(this);
  29159. return this;
  29160. };
  29161. // Instances
  29162. /**
  29163. * Creates a new InstancedMesh object from the mesh model.
  29164. * An instance shares the same properties and the same material than its model.
  29165. * Only these properties of each instance can then be set individually :
  29166. * - position
  29167. * - rotation
  29168. * - rotationQuaternion
  29169. * - setPivotMatrix
  29170. * - scaling
  29171. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29172. * Warning : this method is not supported for Line mesh and LineSystem
  29173. */
  29174. Mesh.prototype.createInstance = function (name) {
  29175. return new BABYLON.InstancedMesh(name, this);
  29176. };
  29177. /**
  29178. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29179. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29180. * This method returns the Mesh.
  29181. */
  29182. Mesh.prototype.synchronizeInstances = function () {
  29183. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29184. var instance = this.instances[instanceIndex];
  29185. instance._syncSubMeshes();
  29186. }
  29187. return this;
  29188. };
  29189. /**
  29190. * Simplify the mesh according to the given array of settings.
  29191. * Function will return immediately and will simplify async. It returns the Mesh.
  29192. * @param settings a collection of simplification settings.
  29193. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29194. * @param type the type of simplification to run.
  29195. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29196. */
  29197. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29198. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29199. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29200. this.getScene().simplificationQueue.addTask({
  29201. settings: settings,
  29202. parallelProcessing: parallelProcessing,
  29203. mesh: this,
  29204. simplificationType: simplificationType,
  29205. successCallback: successCallback
  29206. });
  29207. return this;
  29208. };
  29209. /**
  29210. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29211. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29212. * This should be used together with the simplification to avoid disappearing triangles.
  29213. * Returns the Mesh.
  29214. * @param successCallback an optional success callback to be called after the optimization finished.
  29215. */
  29216. Mesh.prototype.optimizeIndices = function (successCallback) {
  29217. var _this = this;
  29218. var indices = this.getIndices();
  29219. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29220. if (!positions || !indices) {
  29221. return this;
  29222. }
  29223. var vectorPositions = new Array();
  29224. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29225. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29226. }
  29227. var dupes = new Array();
  29228. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29229. var realPos = vectorPositions.length - 1 - iteration;
  29230. var testedPosition = vectorPositions[realPos];
  29231. for (var j = 0; j < realPos; ++j) {
  29232. var againstPosition = vectorPositions[j];
  29233. if (testedPosition.equals(againstPosition)) {
  29234. dupes[realPos] = j;
  29235. break;
  29236. }
  29237. }
  29238. }, function () {
  29239. for (var i = 0; i < indices.length; ++i) {
  29240. indices[i] = dupes[indices[i]] || indices[i];
  29241. }
  29242. //indices are now reordered
  29243. var originalSubMeshes = _this.subMeshes.slice(0);
  29244. _this.setIndices(indices);
  29245. _this.subMeshes = originalSubMeshes;
  29246. if (successCallback) {
  29247. successCallback(_this);
  29248. }
  29249. });
  29250. return this;
  29251. };
  29252. Mesh.prototype.serialize = function (serializationObject) {
  29253. serializationObject.name = this.name;
  29254. serializationObject.id = this.id;
  29255. serializationObject.type = this.getClassName();
  29256. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29257. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29258. }
  29259. serializationObject.position = this.position.asArray();
  29260. if (this.rotationQuaternion) {
  29261. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29262. }
  29263. else if (this.rotation) {
  29264. serializationObject.rotation = this.rotation.asArray();
  29265. }
  29266. serializationObject.scaling = this.scaling.asArray();
  29267. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29268. serializationObject.isEnabled = this.isEnabled(false);
  29269. serializationObject.isVisible = this.isVisible;
  29270. serializationObject.infiniteDistance = this.infiniteDistance;
  29271. serializationObject.pickable = this.isPickable;
  29272. serializationObject.receiveShadows = this.receiveShadows;
  29273. serializationObject.billboardMode = this.billboardMode;
  29274. serializationObject.visibility = this.visibility;
  29275. serializationObject.checkCollisions = this.checkCollisions;
  29276. serializationObject.isBlocker = this.isBlocker;
  29277. // Parent
  29278. if (this.parent) {
  29279. serializationObject.parentId = this.parent.id;
  29280. }
  29281. // Geometry
  29282. serializationObject.isUnIndexed = this.isUnIndexed;
  29283. var geometry = this._geometry;
  29284. if (geometry) {
  29285. var geometryId = geometry.id;
  29286. serializationObject.geometryId = geometryId;
  29287. // SubMeshes
  29288. serializationObject.subMeshes = [];
  29289. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29290. var subMesh = this.subMeshes[subIndex];
  29291. serializationObject.subMeshes.push({
  29292. materialIndex: subMesh.materialIndex,
  29293. verticesStart: subMesh.verticesStart,
  29294. verticesCount: subMesh.verticesCount,
  29295. indexStart: subMesh.indexStart,
  29296. indexCount: subMesh.indexCount
  29297. });
  29298. }
  29299. }
  29300. // Material
  29301. if (this.material) {
  29302. serializationObject.materialId = this.material.id;
  29303. }
  29304. else {
  29305. this.material = null;
  29306. }
  29307. // Morph targets
  29308. if (this.morphTargetManager) {
  29309. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29310. }
  29311. // Skeleton
  29312. if (this.skeleton) {
  29313. serializationObject.skeletonId = this.skeleton.id;
  29314. }
  29315. // Physics
  29316. //TODO implement correct serialization for physics impostors.
  29317. var impostor = this.getPhysicsImpostor();
  29318. if (impostor) {
  29319. serializationObject.physicsMass = impostor.getParam("mass");
  29320. serializationObject.physicsFriction = impostor.getParam("friction");
  29321. serializationObject.physicsRestitution = impostor.getParam("mass");
  29322. serializationObject.physicsImpostor = impostor.type;
  29323. }
  29324. // Metadata
  29325. if (this.metadata) {
  29326. serializationObject.metadata = this.metadata;
  29327. }
  29328. // Instances
  29329. serializationObject.instances = [];
  29330. for (var index = 0; index < this.instances.length; index++) {
  29331. var instance = this.instances[index];
  29332. var serializationInstance = {
  29333. name: instance.name,
  29334. id: instance.id,
  29335. position: instance.position.asArray(),
  29336. scaling: instance.scaling.asArray()
  29337. };
  29338. if (instance.rotationQuaternion) {
  29339. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29340. }
  29341. else if (instance.rotation) {
  29342. serializationInstance.rotation = instance.rotation.asArray();
  29343. }
  29344. serializationObject.instances.push(serializationInstance);
  29345. // Animations
  29346. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29347. serializationInstance.ranges = instance.serializeAnimationRanges();
  29348. }
  29349. //
  29350. // Animations
  29351. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29352. serializationObject.ranges = this.serializeAnimationRanges();
  29353. // Layer mask
  29354. serializationObject.layerMask = this.layerMask;
  29355. // Alpha
  29356. serializationObject.alphaIndex = this.alphaIndex;
  29357. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29358. // Overlay
  29359. serializationObject.overlayAlpha = this.overlayAlpha;
  29360. serializationObject.overlayColor = this.overlayColor.asArray();
  29361. serializationObject.renderOverlay = this.renderOverlay;
  29362. // Fog
  29363. serializationObject.applyFog = this.applyFog;
  29364. // Action Manager
  29365. if (this.actionManager) {
  29366. serializationObject.actions = this.actionManager.serialize(this.name);
  29367. }
  29368. };
  29369. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29370. if (!this.geometry) {
  29371. return;
  29372. }
  29373. this._markSubMeshesAsAttributesDirty();
  29374. var morphTargetManager = this._morphTargetManager;
  29375. if (morphTargetManager && morphTargetManager.vertexCount) {
  29376. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29377. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29378. this.morphTargetManager = null;
  29379. return;
  29380. }
  29381. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29382. var morphTarget = morphTargetManager.getActiveTarget(index);
  29383. var positions = morphTarget.getPositions();
  29384. if (!positions) {
  29385. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29386. return;
  29387. }
  29388. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29389. var normals = morphTarget.getNormals();
  29390. if (normals) {
  29391. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29392. }
  29393. var tangents = morphTarget.getTangents();
  29394. if (tangents) {
  29395. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29396. }
  29397. }
  29398. }
  29399. else {
  29400. var index = 0;
  29401. // Positions
  29402. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29403. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29404. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29405. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29406. }
  29407. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29408. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29409. }
  29410. index++;
  29411. }
  29412. }
  29413. };
  29414. // Statics
  29415. /**
  29416. * Returns a new Mesh object parsed from the source provided.
  29417. * The parameter `parsedMesh` is the source.
  29418. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29419. */
  29420. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29421. var mesh;
  29422. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29423. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29424. }
  29425. else {
  29426. mesh = new Mesh(parsedMesh.name, scene);
  29427. }
  29428. mesh.id = parsedMesh.id;
  29429. if (BABYLON.Tags) {
  29430. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29431. }
  29432. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29433. if (parsedMesh.metadata !== undefined) {
  29434. mesh.metadata = parsedMesh.metadata;
  29435. }
  29436. if (parsedMesh.rotationQuaternion) {
  29437. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29438. }
  29439. else if (parsedMesh.rotation) {
  29440. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29441. }
  29442. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29443. if (parsedMesh.localMatrix) {
  29444. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29445. }
  29446. else if (parsedMesh.pivotMatrix) {
  29447. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29448. }
  29449. mesh.setEnabled(parsedMesh.isEnabled);
  29450. mesh.isVisible = parsedMesh.isVisible;
  29451. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29452. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29453. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29454. if (parsedMesh.applyFog !== undefined) {
  29455. mesh.applyFog = parsedMesh.applyFog;
  29456. }
  29457. if (parsedMesh.pickable !== undefined) {
  29458. mesh.isPickable = parsedMesh.pickable;
  29459. }
  29460. if (parsedMesh.alphaIndex !== undefined) {
  29461. mesh.alphaIndex = parsedMesh.alphaIndex;
  29462. }
  29463. mesh.receiveShadows = parsedMesh.receiveShadows;
  29464. mesh.billboardMode = parsedMesh.billboardMode;
  29465. if (parsedMesh.visibility !== undefined) {
  29466. mesh.visibility = parsedMesh.visibility;
  29467. }
  29468. mesh.checkCollisions = parsedMesh.checkCollisions;
  29469. if (parsedMesh.isBlocker !== undefined) {
  29470. mesh.isBlocker = parsedMesh.isBlocker;
  29471. }
  29472. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29473. // freezeWorldMatrix
  29474. if (parsedMesh.freezeWorldMatrix) {
  29475. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29476. }
  29477. // Parent
  29478. if (parsedMesh.parentId) {
  29479. mesh._waitingParentId = parsedMesh.parentId;
  29480. }
  29481. // Actions
  29482. if (parsedMesh.actions !== undefined) {
  29483. mesh._waitingActions = parsedMesh.actions;
  29484. }
  29485. // Overlay
  29486. if (parsedMesh.overlayAlpha !== undefined) {
  29487. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29488. }
  29489. if (parsedMesh.overlayColor !== undefined) {
  29490. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29491. }
  29492. if (parsedMesh.renderOverlay !== undefined) {
  29493. mesh.renderOverlay = parsedMesh.renderOverlay;
  29494. }
  29495. // Geometry
  29496. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29497. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29498. if (parsedMesh.delayLoadingFile) {
  29499. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29500. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29501. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29502. if (parsedMesh._binaryInfo) {
  29503. mesh._binaryInfo = parsedMesh._binaryInfo;
  29504. }
  29505. mesh._delayInfo = [];
  29506. if (parsedMesh.hasUVs) {
  29507. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29508. }
  29509. if (parsedMesh.hasUVs2) {
  29510. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29511. }
  29512. if (parsedMesh.hasUVs3) {
  29513. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29514. }
  29515. if (parsedMesh.hasUVs4) {
  29516. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29517. }
  29518. if (parsedMesh.hasUVs5) {
  29519. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29520. }
  29521. if (parsedMesh.hasUVs6) {
  29522. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29523. }
  29524. if (parsedMesh.hasColors) {
  29525. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29526. }
  29527. if (parsedMesh.hasMatricesIndices) {
  29528. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29529. }
  29530. if (parsedMesh.hasMatricesWeights) {
  29531. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29532. }
  29533. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29534. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29535. mesh._checkDelayState();
  29536. }
  29537. }
  29538. else {
  29539. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29540. }
  29541. // Material
  29542. if (parsedMesh.materialId) {
  29543. mesh.setMaterialByID(parsedMesh.materialId);
  29544. }
  29545. else {
  29546. mesh.material = null;
  29547. }
  29548. // Morph targets
  29549. if (parsedMesh.morphTargetManagerId > -1) {
  29550. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29551. }
  29552. // Skeleton
  29553. if (parsedMesh.skeletonId > -1) {
  29554. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29555. if (parsedMesh.numBoneInfluencers) {
  29556. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29557. }
  29558. }
  29559. // Animations
  29560. if (parsedMesh.animations) {
  29561. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29562. var parsedAnimation = parsedMesh.animations[animationIndex];
  29563. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29564. }
  29565. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29566. }
  29567. if (parsedMesh.autoAnimate) {
  29568. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29569. }
  29570. // Layer Mask
  29571. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29572. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29573. }
  29574. else {
  29575. mesh.layerMask = 0x0FFFFFFF;
  29576. }
  29577. // Physics
  29578. if (parsedMesh.physicsImpostor) {
  29579. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29580. mass: parsedMesh.physicsMass,
  29581. friction: parsedMesh.physicsFriction,
  29582. restitution: parsedMesh.physicsRestitution
  29583. }, scene);
  29584. }
  29585. // Instances
  29586. if (parsedMesh.instances) {
  29587. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29588. var parsedInstance = parsedMesh.instances[index];
  29589. var instance = mesh.createInstance(parsedInstance.name);
  29590. if (parsedInstance.id) {
  29591. instance.id = parsedInstance.id;
  29592. }
  29593. if (BABYLON.Tags) {
  29594. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29595. }
  29596. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29597. if (parsedInstance.parentId) {
  29598. instance._waitingParentId = parsedInstance.parentId;
  29599. }
  29600. if (parsedInstance.rotationQuaternion) {
  29601. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29602. }
  29603. else if (parsedInstance.rotation) {
  29604. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29605. }
  29606. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29607. instance.checkCollisions = mesh.checkCollisions;
  29608. if (parsedMesh.animations) {
  29609. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29610. parsedAnimation = parsedMesh.animations[animationIndex];
  29611. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29612. }
  29613. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29614. }
  29615. }
  29616. }
  29617. return mesh;
  29618. };
  29619. /**
  29620. * Creates a ribbon mesh.
  29621. * Please consider using the same method from the MeshBuilder class instead.
  29622. * 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.
  29623. *
  29624. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29625. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29626. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29627. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29628. * 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.
  29629. * 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.
  29630. * 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
  29631. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29632. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29633. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29634. */
  29635. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29636. if (closeArray === void 0) { closeArray = false; }
  29637. if (updatable === void 0) { updatable = false; }
  29638. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29639. pathArray: pathArray,
  29640. closeArray: closeArray,
  29641. closePath: closePath,
  29642. offset: offset,
  29643. updatable: updatable,
  29644. sideOrientation: sideOrientation,
  29645. instance: instance
  29646. }, scene);
  29647. };
  29648. /**
  29649. * Creates a plane polygonal mesh. By default, this is a disc.
  29650. * Please consider using the same method from the MeshBuilder class instead.
  29651. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29652. * 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.
  29653. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29654. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29655. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29656. */
  29657. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29658. if (scene === void 0) { scene = null; }
  29659. var options = {
  29660. radius: radius,
  29661. tessellation: tessellation,
  29662. sideOrientation: sideOrientation,
  29663. updatable: updatable
  29664. };
  29665. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29666. };
  29667. /**
  29668. * Creates a box mesh.
  29669. * Please consider using the same method from the MeshBuilder class instead.
  29670. * The parameter `size` sets the size (float) of each box side (default 1).
  29671. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29672. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29673. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29674. */
  29675. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29676. if (scene === void 0) { scene = null; }
  29677. var options = {
  29678. size: size,
  29679. sideOrientation: sideOrientation,
  29680. updatable: updatable
  29681. };
  29682. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29683. };
  29684. /**
  29685. * Creates a sphere mesh.
  29686. * Please consider using the same method from the MeshBuilder class instead.
  29687. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29688. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29689. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29690. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29691. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29692. */
  29693. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29694. var options = {
  29695. segments: segments,
  29696. diameterX: diameter,
  29697. diameterY: diameter,
  29698. diameterZ: diameter,
  29699. sideOrientation: sideOrientation,
  29700. updatable: updatable
  29701. };
  29702. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29703. };
  29704. /**
  29705. * Creates a cylinder or a cone mesh.
  29706. * Please consider using the same method from the MeshBuilder class instead.
  29707. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29708. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29709. * 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.
  29710. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29711. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29712. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29713. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29714. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29715. */
  29716. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29717. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29718. if (scene !== undefined) {
  29719. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29720. updatable = scene;
  29721. }
  29722. scene = subdivisions;
  29723. subdivisions = 1;
  29724. }
  29725. var options = {
  29726. height: height,
  29727. diameterTop: diameterTop,
  29728. diameterBottom: diameterBottom,
  29729. tessellation: tessellation,
  29730. subdivisions: subdivisions,
  29731. sideOrientation: sideOrientation,
  29732. updatable: updatable
  29733. };
  29734. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29735. };
  29736. // Torus (Code from SharpDX.org)
  29737. /**
  29738. * Creates a torus mesh.
  29739. * Please consider using the same method from the MeshBuilder class instead.
  29740. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29741. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29742. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29743. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29744. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29745. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29746. */
  29747. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29748. var options = {
  29749. diameter: diameter,
  29750. thickness: thickness,
  29751. tessellation: tessellation,
  29752. sideOrientation: sideOrientation,
  29753. updatable: updatable
  29754. };
  29755. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29756. };
  29757. /**
  29758. * Creates a torus knot mesh.
  29759. * Please consider using the same method from the MeshBuilder class instead.
  29760. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29761. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29762. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29763. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29764. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29765. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29766. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29767. */
  29768. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29769. var options = {
  29770. radius: radius,
  29771. tube: tube,
  29772. radialSegments: radialSegments,
  29773. tubularSegments: tubularSegments,
  29774. p: p,
  29775. q: q,
  29776. sideOrientation: sideOrientation,
  29777. updatable: updatable
  29778. };
  29779. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29780. };
  29781. /**
  29782. * Creates a line mesh.
  29783. * Please consider using the same method from the MeshBuilder class instead.
  29784. * 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.
  29785. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29786. * The parameter `points` is an array successive Vector3.
  29787. * 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
  29788. * When updating an instance, remember that only point positions can change, not the number of points.
  29789. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29790. */
  29791. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29792. if (scene === void 0) { scene = null; }
  29793. if (updatable === void 0) { updatable = false; }
  29794. if (instance === void 0) { instance = null; }
  29795. var options = {
  29796. points: points,
  29797. updatable: updatable,
  29798. instance: instance
  29799. };
  29800. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29801. };
  29802. /**
  29803. * Creates a dashed line mesh.
  29804. * Please consider using the same method from the MeshBuilder class instead.
  29805. * 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.
  29806. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29807. * The parameter `points` is an array successive Vector3.
  29808. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29809. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29810. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29811. * 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
  29812. * When updating an instance, remember that only point positions can change, not the number of points.
  29813. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29814. */
  29815. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29816. if (scene === void 0) { scene = null; }
  29817. var options = {
  29818. points: points,
  29819. dashSize: dashSize,
  29820. gapSize: gapSize,
  29821. dashNb: dashNb,
  29822. updatable: updatable,
  29823. instance: instance
  29824. };
  29825. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29826. };
  29827. /**
  29828. * Creates a polygon mesh.
  29829. * Please consider using the same method from the MeshBuilder class instead.
  29830. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29831. * 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.
  29832. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29833. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29834. * Remember you can only change the shape positions, not their number when updating a polygon.
  29835. */
  29836. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29837. var options = {
  29838. shape: shape,
  29839. holes: holes,
  29840. updatable: updatable,
  29841. sideOrientation: sideOrientation
  29842. };
  29843. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29844. };
  29845. /**
  29846. * Creates an extruded polygon mesh, with depth in the Y direction.
  29847. * Please consider using the same method from the MeshBuilder class instead.
  29848. */
  29849. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29850. var options = {
  29851. shape: shape,
  29852. holes: holes,
  29853. depth: depth,
  29854. updatable: updatable,
  29855. sideOrientation: sideOrientation
  29856. };
  29857. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29858. };
  29859. /**
  29860. * Creates an extruded shape mesh.
  29861. * 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.
  29862. * Please consider using the same method from the MeshBuilder class instead.
  29863. *
  29864. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29865. * 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
  29866. * extruded along the Z axis.
  29867. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29868. * 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.
  29869. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29870. * 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
  29871. * 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
  29872. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29873. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29874. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29875. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29876. */
  29877. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29878. if (scene === void 0) { scene = null; }
  29879. var options = {
  29880. shape: shape,
  29881. path: path,
  29882. scale: scale,
  29883. rotation: rotation,
  29884. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29885. sideOrientation: sideOrientation,
  29886. instance: instance,
  29887. updatable: updatable
  29888. };
  29889. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29890. };
  29891. /**
  29892. * Creates an custom extruded shape mesh.
  29893. * 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.
  29894. * Please consider using the same method from the MeshBuilder class instead.
  29895. *
  29896. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29897. * 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
  29898. * extruded along the Z axis.
  29899. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29900. * 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
  29901. * and the distance of this point from the begining of the path :
  29902. * ```javascript
  29903. * var rotationFunction = function(i, distance) {
  29904. * // do things
  29905. * return rotationValue; }
  29906. * ```
  29907. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29908. * 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
  29909. * and the distance of this point from the begining of the path :
  29910. * ```javascript
  29911. * var scaleFunction = function(i, distance) {
  29912. * // do things
  29913. * return scaleValue;}
  29914. * ```
  29915. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29916. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29917. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29918. * 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
  29919. * 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
  29920. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29921. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29922. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29923. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29924. */
  29925. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29926. var options = {
  29927. shape: shape,
  29928. path: path,
  29929. scaleFunction: scaleFunction,
  29930. rotationFunction: rotationFunction,
  29931. ribbonCloseArray: ribbonCloseArray,
  29932. ribbonClosePath: ribbonClosePath,
  29933. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29934. sideOrientation: sideOrientation,
  29935. instance: instance,
  29936. updatable: updatable
  29937. };
  29938. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29939. };
  29940. /**
  29941. * Creates lathe mesh.
  29942. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29943. * Please consider using the same method from the MeshBuilder class instead.
  29944. * 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
  29945. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29946. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29947. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29948. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29949. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29950. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29951. */
  29952. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29953. var options = {
  29954. shape: shape,
  29955. radius: radius,
  29956. tessellation: tessellation,
  29957. sideOrientation: sideOrientation,
  29958. updatable: updatable
  29959. };
  29960. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29961. };
  29962. /**
  29963. * Creates a plane mesh.
  29964. * Please consider using the same method from the MeshBuilder class instead.
  29965. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29966. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29967. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29968. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29969. */
  29970. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29971. var options = {
  29972. size: size,
  29973. width: size,
  29974. height: size,
  29975. sideOrientation: sideOrientation,
  29976. updatable: updatable
  29977. };
  29978. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29979. };
  29980. /**
  29981. * Creates a ground mesh.
  29982. * Please consider using the same method from the MeshBuilder class instead.
  29983. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29984. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29985. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29986. */
  29987. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29988. var options = {
  29989. width: width,
  29990. height: height,
  29991. subdivisions: subdivisions,
  29992. updatable: updatable
  29993. };
  29994. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29995. };
  29996. /**
  29997. * Creates a tiled ground mesh.
  29998. * Please consider using the same method from the MeshBuilder class instead.
  29999. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30000. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30001. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30002. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30003. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30004. * numbers of subdivisions on the ground width and height of each tile.
  30005. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30006. */
  30007. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30008. var options = {
  30009. xmin: xmin,
  30010. zmin: zmin,
  30011. xmax: xmax,
  30012. zmax: zmax,
  30013. subdivisions: subdivisions,
  30014. precision: precision,
  30015. updatable: updatable
  30016. };
  30017. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30018. };
  30019. /**
  30020. * Creates a ground mesh from a height map.
  30021. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30022. * Please consider using the same method from the MeshBuilder class instead.
  30023. * The parameter `url` sets the URL of the height map image resource.
  30024. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30025. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30026. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30027. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30028. * 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).
  30029. * This function is passed the newly built mesh :
  30030. * ```javascript
  30031. * function(mesh) { // do things
  30032. * return; }
  30033. * ```
  30034. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30035. */
  30036. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30037. var options = {
  30038. width: width,
  30039. height: height,
  30040. subdivisions: subdivisions,
  30041. minHeight: minHeight,
  30042. maxHeight: maxHeight,
  30043. updatable: updatable,
  30044. onReady: onReady
  30045. };
  30046. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30047. };
  30048. /**
  30049. * Creates a tube mesh.
  30050. * 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.
  30051. * Please consider using the same method from the MeshBuilder class instead.
  30052. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30053. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30054. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30055. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30056. * 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.
  30057. * It must return a radius value (positive float) :
  30058. * ```javascript
  30059. * var radiusFunction = function(i, distance) {
  30060. * // do things
  30061. * return radius; }
  30062. * ```
  30063. * 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
  30064. * 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
  30065. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30066. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30067. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30068. */
  30069. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30070. var options = {
  30071. path: path,
  30072. radius: radius,
  30073. tessellation: tessellation,
  30074. radiusFunction: radiusFunction,
  30075. arc: 1,
  30076. cap: cap,
  30077. updatable: updatable,
  30078. sideOrientation: sideOrientation,
  30079. instance: instance
  30080. };
  30081. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30082. };
  30083. /**
  30084. * Creates a polyhedron mesh.
  30085. * Please consider using the same method from the MeshBuilder class instead.
  30086. * 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
  30087. * to choose the wanted type.
  30088. * The parameter `size` (positive float, default 1) sets the polygon size.
  30089. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30090. * 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`.
  30091. * 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
  30092. * 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)`).
  30093. * 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
  30094. * 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.
  30095. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30096. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30097. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30098. */
  30099. Mesh.CreatePolyhedron = function (name, options, scene) {
  30100. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30101. };
  30102. /**
  30103. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30104. * Please consider using the same method from the MeshBuilder class instead.
  30105. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30106. * 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`).
  30107. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30108. * 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.
  30109. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30110. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30111. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30112. */
  30113. Mesh.CreateIcoSphere = function (name, options, scene) {
  30114. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30115. };
  30116. /**
  30117. * Creates a decal mesh.
  30118. * Please consider using the same method from the MeshBuilder class instead.
  30119. * 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.
  30120. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30121. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30122. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30123. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30124. */
  30125. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30126. var options = {
  30127. position: position,
  30128. normal: normal,
  30129. size: size,
  30130. angle: angle
  30131. };
  30132. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30133. };
  30134. // Skeletons
  30135. /**
  30136. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30137. */
  30138. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30139. if (!this._sourcePositions) {
  30140. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30141. if (!source) {
  30142. return this._sourcePositions;
  30143. }
  30144. this._sourcePositions = new Float32Array(source);
  30145. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30146. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30147. }
  30148. }
  30149. return this._sourcePositions;
  30150. };
  30151. /**
  30152. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30153. */
  30154. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30155. if (!this._sourceNormals) {
  30156. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30157. if (!source) {
  30158. return this._sourceNormals;
  30159. }
  30160. this._sourceNormals = new Float32Array(source);
  30161. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30162. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30163. }
  30164. }
  30165. return this._sourceNormals;
  30166. };
  30167. /**
  30168. * Updates the vertex buffer by applying transformation from the bones.
  30169. * Returns the Mesh.
  30170. *
  30171. * @param {skeleton} skeleton to apply
  30172. */
  30173. Mesh.prototype.applySkeleton = function (skeleton) {
  30174. if (!this.geometry) {
  30175. return this;
  30176. }
  30177. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30178. return this;
  30179. }
  30180. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30181. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30182. return this;
  30183. }
  30184. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30185. return this;
  30186. }
  30187. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30188. return this;
  30189. }
  30190. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30191. return this;
  30192. }
  30193. if (!this._sourcePositions) {
  30194. var submeshes = this.subMeshes.slice();
  30195. this.setPositionsForCPUSkinning();
  30196. this.subMeshes = submeshes;
  30197. }
  30198. if (!this._sourceNormals) {
  30199. this.setNormalsForCPUSkinning();
  30200. }
  30201. // positionsData checks for not being Float32Array will only pass at most once
  30202. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30203. if (!positionsData) {
  30204. return this;
  30205. }
  30206. if (!(positionsData instanceof Float32Array)) {
  30207. positionsData = new Float32Array(positionsData);
  30208. }
  30209. // normalsData checks for not being Float32Array will only pass at most once
  30210. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30211. if (!normalsData) {
  30212. return this;
  30213. }
  30214. if (!(normalsData instanceof Float32Array)) {
  30215. normalsData = new Float32Array(normalsData);
  30216. }
  30217. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30218. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30219. if (!matricesWeightsData || !matricesIndicesData) {
  30220. return this;
  30221. }
  30222. var needExtras = this.numBoneInfluencers > 4;
  30223. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30224. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30225. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30226. var tempVector3 = BABYLON.Vector3.Zero();
  30227. var finalMatrix = new BABYLON.Matrix();
  30228. var tempMatrix = new BABYLON.Matrix();
  30229. var matWeightIdx = 0;
  30230. var inf;
  30231. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30232. var weight;
  30233. for (inf = 0; inf < 4; inf++) {
  30234. weight = matricesWeightsData[matWeightIdx + inf];
  30235. if (weight > 0) {
  30236. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30237. finalMatrix.addToSelf(tempMatrix);
  30238. }
  30239. else
  30240. break;
  30241. }
  30242. if (needExtras) {
  30243. for (inf = 0; inf < 4; inf++) {
  30244. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30245. if (weight > 0) {
  30246. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30247. finalMatrix.addToSelf(tempMatrix);
  30248. }
  30249. else
  30250. break;
  30251. }
  30252. }
  30253. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30254. tempVector3.toArray(positionsData, index);
  30255. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30256. tempVector3.toArray(normalsData, index);
  30257. finalMatrix.reset();
  30258. }
  30259. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30260. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30261. return this;
  30262. };
  30263. // Tools
  30264. /**
  30265. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30266. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30267. */
  30268. Mesh.MinMax = function (meshes) {
  30269. var minVector = null;
  30270. var maxVector = null;
  30271. meshes.forEach(function (mesh, index, array) {
  30272. var boundingInfo = mesh.getBoundingInfo();
  30273. var boundingBox = boundingInfo.boundingBox;
  30274. if (!minVector || !maxVector) {
  30275. minVector = boundingBox.minimumWorld;
  30276. maxVector = boundingBox.maximumWorld;
  30277. }
  30278. else {
  30279. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30280. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30281. }
  30282. });
  30283. if (!minVector || !maxVector) {
  30284. return {
  30285. min: BABYLON.Vector3.Zero(),
  30286. max: BABYLON.Vector3.Zero()
  30287. };
  30288. }
  30289. return {
  30290. min: minVector,
  30291. max: maxVector
  30292. };
  30293. };
  30294. /**
  30295. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30296. */
  30297. Mesh.Center = function (meshesOrMinMaxVector) {
  30298. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30299. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30300. };
  30301. /**
  30302. * Merge the array of meshes into a single mesh for performance reasons.
  30303. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30304. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30305. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30306. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30307. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30308. */
  30309. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30310. if (disposeSource === void 0) { disposeSource = true; }
  30311. var index;
  30312. if (!allow32BitsIndices) {
  30313. var totalVertices = 0;
  30314. // Counting vertices
  30315. for (index = 0; index < meshes.length; index++) {
  30316. if (meshes[index]) {
  30317. totalVertices += meshes[index].getTotalVertices();
  30318. if (totalVertices > 65536) {
  30319. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30320. return null;
  30321. }
  30322. }
  30323. }
  30324. }
  30325. // Merge
  30326. var vertexData = null;
  30327. var otherVertexData;
  30328. var indiceArray = new Array();
  30329. var source = null;
  30330. for (index = 0; index < meshes.length; index++) {
  30331. if (meshes[index]) {
  30332. meshes[index].computeWorldMatrix(true);
  30333. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30334. otherVertexData.transform(meshes[index].getWorldMatrix());
  30335. if (vertexData) {
  30336. vertexData.merge(otherVertexData);
  30337. }
  30338. else {
  30339. vertexData = otherVertexData;
  30340. source = meshes[index];
  30341. }
  30342. if (subdivideWithSubMeshes) {
  30343. indiceArray.push(meshes[index].getTotalIndices());
  30344. }
  30345. }
  30346. }
  30347. source = source;
  30348. if (!meshSubclass) {
  30349. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30350. }
  30351. vertexData.applyToMesh(meshSubclass);
  30352. // Setting properties
  30353. meshSubclass.material = source.material;
  30354. meshSubclass.checkCollisions = source.checkCollisions;
  30355. // Cleaning
  30356. if (disposeSource) {
  30357. for (index = 0; index < meshes.length; index++) {
  30358. if (meshes[index]) {
  30359. meshes[index].dispose();
  30360. }
  30361. }
  30362. }
  30363. // Subdivide
  30364. if (subdivideWithSubMeshes) {
  30365. //-- Suppresions du submesh global
  30366. meshSubclass.releaseSubMeshes();
  30367. index = 0;
  30368. var offset = 0;
  30369. //-- aplique la subdivision en fonction du tableau d'indices
  30370. while (index < indiceArray.length) {
  30371. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30372. offset += indiceArray[index];
  30373. index++;
  30374. }
  30375. }
  30376. return meshSubclass;
  30377. };
  30378. // Consts
  30379. Mesh._FRONTSIDE = 0;
  30380. Mesh._BACKSIDE = 1;
  30381. Mesh._DOUBLESIDE = 2;
  30382. Mesh._DEFAULTSIDE = 0;
  30383. Mesh._NO_CAP = 0;
  30384. Mesh._CAP_START = 1;
  30385. Mesh._CAP_END = 2;
  30386. Mesh._CAP_ALL = 3;
  30387. return Mesh;
  30388. }(BABYLON.AbstractMesh));
  30389. BABYLON.Mesh = Mesh;
  30390. })(BABYLON || (BABYLON = {}));
  30391. //# sourceMappingURL=babylon.mesh.js.map
  30392. var BABYLON;
  30393. (function (BABYLON) {
  30394. var BaseSubMesh = /** @class */ (function () {
  30395. function BaseSubMesh() {
  30396. }
  30397. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30398. get: function () {
  30399. return this._materialEffect;
  30400. },
  30401. enumerable: true,
  30402. configurable: true
  30403. });
  30404. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30405. if (defines === void 0) { defines = null; }
  30406. if (this._materialEffect === effect) {
  30407. if (!effect) {
  30408. this._materialDefines = null;
  30409. }
  30410. return;
  30411. }
  30412. this._materialDefines = defines;
  30413. this._materialEffect = effect;
  30414. };
  30415. return BaseSubMesh;
  30416. }());
  30417. BABYLON.BaseSubMesh = BaseSubMesh;
  30418. var SubMesh = /** @class */ (function (_super) {
  30419. __extends(SubMesh, _super);
  30420. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30421. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30422. var _this = _super.call(this) || this;
  30423. _this.materialIndex = materialIndex;
  30424. _this.verticesStart = verticesStart;
  30425. _this.verticesCount = verticesCount;
  30426. _this.indexStart = indexStart;
  30427. _this.indexCount = indexCount;
  30428. _this._renderId = 0;
  30429. _this._mesh = mesh;
  30430. _this._renderingMesh = renderingMesh || mesh;
  30431. mesh.subMeshes.push(_this);
  30432. _this._trianglePlanes = [];
  30433. _this._id = mesh.subMeshes.length - 1;
  30434. if (createBoundingBox) {
  30435. _this.refreshBoundingInfo();
  30436. mesh.computeWorldMatrix(true);
  30437. }
  30438. return _this;
  30439. }
  30440. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30441. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30442. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30443. };
  30444. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30445. get: function () {
  30446. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30447. },
  30448. enumerable: true,
  30449. configurable: true
  30450. });
  30451. /**
  30452. * Returns the submesh BoudingInfo object.
  30453. */
  30454. SubMesh.prototype.getBoundingInfo = function () {
  30455. if (this.IsGlobal) {
  30456. return this._mesh.getBoundingInfo();
  30457. }
  30458. return this._boundingInfo;
  30459. };
  30460. /**
  30461. * Sets the submesh BoundingInfo.
  30462. * Return the SubMesh.
  30463. */
  30464. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30465. this._boundingInfo = boundingInfo;
  30466. return this;
  30467. };
  30468. /**
  30469. * Returns the mesh of the current submesh.
  30470. */
  30471. SubMesh.prototype.getMesh = function () {
  30472. return this._mesh;
  30473. };
  30474. /**
  30475. * Returns the rendering mesh of the submesh.
  30476. */
  30477. SubMesh.prototype.getRenderingMesh = function () {
  30478. return this._renderingMesh;
  30479. };
  30480. /**
  30481. * Returns the submesh material.
  30482. */
  30483. SubMesh.prototype.getMaterial = function () {
  30484. var rootMaterial = this._renderingMesh.material;
  30485. if (rootMaterial === null || rootMaterial === undefined) {
  30486. return this._mesh.getScene().defaultMaterial;
  30487. }
  30488. else if (rootMaterial.getSubMaterial) {
  30489. var multiMaterial = rootMaterial;
  30490. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30491. if (this._currentMaterial !== effectiveMaterial) {
  30492. this._currentMaterial = effectiveMaterial;
  30493. this._materialDefines = null;
  30494. }
  30495. return effectiveMaterial;
  30496. }
  30497. return rootMaterial;
  30498. };
  30499. // Methods
  30500. /**
  30501. * Sets a new updated BoundingInfo object to the submesh.
  30502. * Returns the SubMesh.
  30503. */
  30504. SubMesh.prototype.refreshBoundingInfo = function () {
  30505. this._lastColliderWorldVertices = null;
  30506. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30507. return this;
  30508. }
  30509. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30510. if (!data) {
  30511. this._boundingInfo = this._mesh.getBoundingInfo();
  30512. return this;
  30513. }
  30514. var indices = this._renderingMesh.getIndices();
  30515. var extend;
  30516. //is this the only submesh?
  30517. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30518. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30519. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30520. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30521. }
  30522. else {
  30523. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30524. }
  30525. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30526. return this;
  30527. };
  30528. SubMesh.prototype._checkCollision = function (collider) {
  30529. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30530. return boundingInfo._checkCollision(collider);
  30531. };
  30532. /**
  30533. * Updates the submesh BoundingInfo.
  30534. * Returns the Submesh.
  30535. */
  30536. SubMesh.prototype.updateBoundingInfo = function (world) {
  30537. var boundingInfo = this.getBoundingInfo();
  30538. if (!boundingInfo) {
  30539. this.refreshBoundingInfo();
  30540. boundingInfo = this.getBoundingInfo();
  30541. }
  30542. boundingInfo.update(world);
  30543. return this;
  30544. };
  30545. /**
  30546. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30547. * Boolean returned.
  30548. */
  30549. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30550. var boundingInfo = this.getBoundingInfo();
  30551. if (!boundingInfo) {
  30552. return false;
  30553. }
  30554. return boundingInfo.isInFrustum(frustumPlanes);
  30555. };
  30556. /**
  30557. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30558. * Boolean returned.
  30559. */
  30560. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30561. var boundingInfo = this.getBoundingInfo();
  30562. if (!boundingInfo) {
  30563. return false;
  30564. }
  30565. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30566. };
  30567. /**
  30568. * Renders the submesh.
  30569. * Returns it.
  30570. */
  30571. SubMesh.prototype.render = function (enableAlphaMode) {
  30572. this._renderingMesh.render(this, enableAlphaMode);
  30573. return this;
  30574. };
  30575. /**
  30576. * Returns a new Index Buffer.
  30577. * Type returned : WebGLBuffer.
  30578. */
  30579. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30580. if (!this._linesIndexBuffer) {
  30581. var linesIndices = [];
  30582. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30583. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30584. }
  30585. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30586. this.linesIndexCount = linesIndices.length;
  30587. }
  30588. return this._linesIndexBuffer;
  30589. };
  30590. /**
  30591. * True is the passed Ray intersects the submesh bounding box.
  30592. * Boolean returned.
  30593. */
  30594. SubMesh.prototype.canIntersects = function (ray) {
  30595. var boundingInfo = this.getBoundingInfo();
  30596. if (!boundingInfo) {
  30597. return false;
  30598. }
  30599. return ray.intersectsBox(boundingInfo.boundingBox);
  30600. };
  30601. /**
  30602. * Returns an object IntersectionInfo.
  30603. */
  30604. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30605. var intersectInfo = null;
  30606. // LineMesh first as it's also a Mesh...
  30607. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30608. var lineMesh = this._mesh;
  30609. // Line test
  30610. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30611. var p0 = positions[indices[index]];
  30612. var p1 = positions[indices[index + 1]];
  30613. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30614. if (length < 0) {
  30615. continue;
  30616. }
  30617. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30618. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30619. if (fastCheck) {
  30620. break;
  30621. }
  30622. }
  30623. }
  30624. }
  30625. else {
  30626. // Triangles test
  30627. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30628. var p0 = positions[indices[index]];
  30629. var p1 = positions[indices[index + 1]];
  30630. var p2 = positions[indices[index + 2]];
  30631. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30632. if (currentIntersectInfo) {
  30633. if (currentIntersectInfo.distance < 0) {
  30634. continue;
  30635. }
  30636. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30637. intersectInfo = currentIntersectInfo;
  30638. intersectInfo.faceId = index / 3;
  30639. if (fastCheck) {
  30640. break;
  30641. }
  30642. }
  30643. }
  30644. }
  30645. }
  30646. return intersectInfo;
  30647. };
  30648. SubMesh.prototype._rebuild = function () {
  30649. if (this._linesIndexBuffer) {
  30650. this._linesIndexBuffer = null;
  30651. }
  30652. };
  30653. // Clone
  30654. /**
  30655. * Creates a new Submesh from the passed Mesh.
  30656. */
  30657. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30658. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30659. if (!this.IsGlobal) {
  30660. var boundingInfo = this.getBoundingInfo();
  30661. if (!boundingInfo) {
  30662. return result;
  30663. }
  30664. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30665. }
  30666. return result;
  30667. };
  30668. // Dispose
  30669. /**
  30670. * Disposes the Submesh.
  30671. * Returns nothing.
  30672. */
  30673. SubMesh.prototype.dispose = function () {
  30674. if (this._linesIndexBuffer) {
  30675. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30676. this._linesIndexBuffer = null;
  30677. }
  30678. // Remove from mesh
  30679. var index = this._mesh.subMeshes.indexOf(this);
  30680. this._mesh.subMeshes.splice(index, 1);
  30681. };
  30682. // Statics
  30683. /**
  30684. * Creates a new Submesh from the passed parameters :
  30685. * - materialIndex (integer) : the index of the main mesh material.
  30686. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30687. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30688. * - mesh (Mesh) : the main mesh to create the submesh from.
  30689. * - renderingMesh (optional Mesh) : rendering mesh.
  30690. */
  30691. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30692. var minVertexIndex = Number.MAX_VALUE;
  30693. var maxVertexIndex = -Number.MAX_VALUE;
  30694. renderingMesh = (renderingMesh || mesh);
  30695. var indices = renderingMesh.getIndices();
  30696. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30697. var vertexIndex = indices[index];
  30698. if (vertexIndex < minVertexIndex)
  30699. minVertexIndex = vertexIndex;
  30700. if (vertexIndex > maxVertexIndex)
  30701. maxVertexIndex = vertexIndex;
  30702. }
  30703. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30704. };
  30705. return SubMesh;
  30706. }(BaseSubMesh));
  30707. BABYLON.SubMesh = SubMesh;
  30708. })(BABYLON || (BABYLON = {}));
  30709. //# sourceMappingURL=babylon.subMesh.js.map
  30710. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30711. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30712. s = arguments[i];
  30713. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30714. t[p] = s[p];
  30715. }
  30716. return t;
  30717. };
  30718. var BABYLON;
  30719. (function (BABYLON) {
  30720. /**
  30721. * Manages the defines for the Material.
  30722. */
  30723. var MaterialDefines = /** @class */ (function () {
  30724. function MaterialDefines() {
  30725. this._isDirty = true;
  30726. this._areLightsDirty = true;
  30727. this._areAttributesDirty = true;
  30728. this._areTexturesDirty = true;
  30729. this._areFresnelDirty = true;
  30730. this._areMiscDirty = true;
  30731. this._areImageProcessingDirty = true;
  30732. this._normals = false;
  30733. this._uvs = false;
  30734. this._needNormals = false;
  30735. this._needUVs = false;
  30736. }
  30737. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30738. /**
  30739. * Specifies if the material needs to be re-calculated.
  30740. */
  30741. get: function () {
  30742. return this._isDirty;
  30743. },
  30744. enumerable: true,
  30745. configurable: true
  30746. });
  30747. /**
  30748. * Marks the material to indicate that it has been re-calculated.
  30749. */
  30750. MaterialDefines.prototype.markAsProcessed = function () {
  30751. this._isDirty = false;
  30752. this._areAttributesDirty = false;
  30753. this._areTexturesDirty = false;
  30754. this._areFresnelDirty = false;
  30755. this._areLightsDirty = false;
  30756. this._areMiscDirty = false;
  30757. this._areImageProcessingDirty = false;
  30758. };
  30759. /**
  30760. * Marks the material to indicate that it needs to be re-calculated.
  30761. */
  30762. MaterialDefines.prototype.markAsUnprocessed = function () {
  30763. this._isDirty = true;
  30764. };
  30765. /**
  30766. * Marks the material to indicate all of its defines need to be re-calculated.
  30767. */
  30768. MaterialDefines.prototype.markAllAsDirty = function () {
  30769. this._areTexturesDirty = true;
  30770. this._areAttributesDirty = true;
  30771. this._areLightsDirty = true;
  30772. this._areFresnelDirty = true;
  30773. this._areMiscDirty = true;
  30774. this._areImageProcessingDirty = true;
  30775. this._isDirty = true;
  30776. };
  30777. /**
  30778. * Marks the material to indicate that image processing needs to be re-calculated.
  30779. */
  30780. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30781. this._areImageProcessingDirty = true;
  30782. this._isDirty = true;
  30783. };
  30784. /**
  30785. * Marks the material to indicate the lights need to be re-calculated.
  30786. */
  30787. MaterialDefines.prototype.markAsLightDirty = function () {
  30788. this._areLightsDirty = true;
  30789. this._isDirty = true;
  30790. };
  30791. /**
  30792. * Marks the attribute state as changed.
  30793. */
  30794. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30795. this._areAttributesDirty = true;
  30796. this._isDirty = true;
  30797. };
  30798. /**
  30799. * Marks the texture state as changed.
  30800. */
  30801. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30802. this._areTexturesDirty = true;
  30803. this._isDirty = true;
  30804. };
  30805. /**
  30806. * Marks the fresnel state as changed.
  30807. */
  30808. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30809. this._areFresnelDirty = true;
  30810. this._isDirty = true;
  30811. };
  30812. /**
  30813. * Marks the misc state as changed.
  30814. */
  30815. MaterialDefines.prototype.markAsMiscDirty = function () {
  30816. this._areMiscDirty = true;
  30817. this._isDirty = true;
  30818. };
  30819. /**
  30820. * Rebuilds the material defines.
  30821. */
  30822. MaterialDefines.prototype.rebuild = function () {
  30823. if (this._keys) {
  30824. delete this._keys;
  30825. }
  30826. this._keys = [];
  30827. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30828. var key = _a[_i];
  30829. if (key[0] === "_") {
  30830. continue;
  30831. }
  30832. this._keys.push(key);
  30833. }
  30834. };
  30835. /**
  30836. * Specifies if two material defines are equal.
  30837. * @param other - A material define instance to compare to.
  30838. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30839. */
  30840. MaterialDefines.prototype.isEqual = function (other) {
  30841. if (this._keys.length !== other._keys.length) {
  30842. return false;
  30843. }
  30844. for (var index = 0; index < this._keys.length; index++) {
  30845. var prop = this._keys[index];
  30846. if (this[prop] !== other[prop]) {
  30847. return false;
  30848. }
  30849. }
  30850. return true;
  30851. };
  30852. /**
  30853. * Clones this instance's defines to another instance.
  30854. * @param other - material defines to clone values to.
  30855. */
  30856. MaterialDefines.prototype.cloneTo = function (other) {
  30857. if (this._keys.length !== other._keys.length) {
  30858. other._keys = this._keys.slice(0);
  30859. }
  30860. for (var index = 0; index < this._keys.length; index++) {
  30861. var prop = this._keys[index];
  30862. other[prop] = this[prop];
  30863. }
  30864. };
  30865. /**
  30866. * Resets the material define values.
  30867. */
  30868. MaterialDefines.prototype.reset = function () {
  30869. for (var index = 0; index < this._keys.length; index++) {
  30870. var prop = this._keys[index];
  30871. if (typeof (this[prop]) === "number") {
  30872. this[prop] = 0;
  30873. }
  30874. else {
  30875. this[prop] = false;
  30876. }
  30877. }
  30878. };
  30879. /**
  30880. * Converts the material define values to a string.
  30881. * @returns - String of material define information.
  30882. */
  30883. MaterialDefines.prototype.toString = function () {
  30884. var result = "";
  30885. for (var index = 0; index < this._keys.length; index++) {
  30886. var prop = this._keys[index];
  30887. var value = this[prop];
  30888. if (typeof (value) === "number") {
  30889. result += "#define " + prop + " " + this[prop] + "\n";
  30890. }
  30891. else if (value) {
  30892. result += "#define " + prop + "\n";
  30893. }
  30894. }
  30895. return result;
  30896. };
  30897. return MaterialDefines;
  30898. }());
  30899. BABYLON.MaterialDefines = MaterialDefines;
  30900. /**
  30901. * This offers the main features of a material in BJS.
  30902. */
  30903. var Material = /** @class */ (function () {
  30904. /**
  30905. * Creates a material instance.
  30906. * @param name - The name of the material.
  30907. * @param scene - The BJS scene to reference.
  30908. * @param doNotAdd - Specifies if the material should be added to the scene.
  30909. */
  30910. function Material(name, scene, doNotAdd) {
  30911. /**
  30912. * Specifies if the ready state should be checked on each call.
  30913. */
  30914. this.checkReadyOnEveryCall = false;
  30915. /**
  30916. * Specifies if the ready state should be checked once.
  30917. */
  30918. this.checkReadyOnlyOnce = false;
  30919. /**
  30920. * The state of the material.
  30921. */
  30922. this.state = "";
  30923. /**
  30924. * The alpha value of the material.
  30925. */
  30926. this._alpha = 1.0;
  30927. /**
  30928. * Specifies if back face culling is enabled.
  30929. */
  30930. this._backFaceCulling = true;
  30931. /**
  30932. * Specifies if the material should be serialized.
  30933. */
  30934. this.doNotSerialize = false;
  30935. /**
  30936. * Specifies if the effect should be stored on sub meshes.
  30937. */
  30938. this.storeEffectOnSubMeshes = false;
  30939. /**
  30940. * An event triggered when the material is disposed.
  30941. * @type {BABYLON.Observable}
  30942. */
  30943. this.onDisposeObservable = new BABYLON.Observable();
  30944. /**
  30945. * An event triggered when the material is bound.
  30946. * @type {BABYLON.Observable}
  30947. */
  30948. this.onBindObservable = new BABYLON.Observable();
  30949. /**
  30950. * An event triggered when the material is unbound.
  30951. * @type {BABYLON.Observable}
  30952. */
  30953. this.onUnBindObservable = new BABYLON.Observable();
  30954. /**
  30955. * Stores the value of the alpha mode.
  30956. */
  30957. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30958. /**
  30959. * Stores the state of the need depth pre-pass value.
  30960. */
  30961. this._needDepthPrePass = false;
  30962. /**
  30963. * Specifies if depth writing should be disabled.
  30964. */
  30965. this.disableDepthWrite = false;
  30966. /**
  30967. * Specifies if depth writing should be forced.
  30968. */
  30969. this.forceDepthWrite = false;
  30970. /**
  30971. * Specifies if there should be a separate pass for culling.
  30972. */
  30973. this.separateCullingPass = false;
  30974. /**
  30975. * Stores the state specifing if fog should be enabled.
  30976. */
  30977. this._fogEnabled = true;
  30978. /**
  30979. * Stores the size of points.
  30980. */
  30981. this.pointSize = 1.0;
  30982. /**
  30983. * Stores the z offset value.
  30984. */
  30985. this.zOffset = 0;
  30986. /**
  30987. * Specifies if the material was previously ready.
  30988. */
  30989. this._wasPreviouslyReady = false;
  30990. /**
  30991. * Stores the fill mode state.
  30992. */
  30993. this._fillMode = Material.TriangleFillMode;
  30994. this.name = name;
  30995. this.id = name || BABYLON.Tools.RandomId();
  30996. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30997. if (this._scene.useRightHandedSystem) {
  30998. this.sideOrientation = Material.ClockWiseSideOrientation;
  30999. }
  31000. else {
  31001. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31002. }
  31003. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31004. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31005. if (!doNotAdd) {
  31006. this._scene.materials.push(this);
  31007. }
  31008. }
  31009. Object.defineProperty(Material, "TriangleFillMode", {
  31010. /**
  31011. * Returns the triangle fill mode.
  31012. */
  31013. get: function () {
  31014. return Material._TriangleFillMode;
  31015. },
  31016. enumerable: true,
  31017. configurable: true
  31018. });
  31019. Object.defineProperty(Material, "WireFrameFillMode", {
  31020. /**
  31021. * Returns the wireframe mode.
  31022. */
  31023. get: function () {
  31024. return Material._WireFrameFillMode;
  31025. },
  31026. enumerable: true,
  31027. configurable: true
  31028. });
  31029. Object.defineProperty(Material, "PointFillMode", {
  31030. /**
  31031. * Returns the point fill mode.
  31032. */
  31033. get: function () {
  31034. return Material._PointFillMode;
  31035. },
  31036. enumerable: true,
  31037. configurable: true
  31038. });
  31039. Object.defineProperty(Material, "PointListDrawMode", {
  31040. /**
  31041. * Returns the point list draw mode.
  31042. */
  31043. get: function () {
  31044. return Material._PointListDrawMode;
  31045. },
  31046. enumerable: true,
  31047. configurable: true
  31048. });
  31049. Object.defineProperty(Material, "LineListDrawMode", {
  31050. /**
  31051. * Returns the line list draw mode.
  31052. */
  31053. get: function () {
  31054. return Material._LineListDrawMode;
  31055. },
  31056. enumerable: true,
  31057. configurable: true
  31058. });
  31059. Object.defineProperty(Material, "LineLoopDrawMode", {
  31060. /**
  31061. * Returns the line loop draw mode.
  31062. */
  31063. get: function () {
  31064. return Material._LineLoopDrawMode;
  31065. },
  31066. enumerable: true,
  31067. configurable: true
  31068. });
  31069. Object.defineProperty(Material, "LineStripDrawMode", {
  31070. /**
  31071. * Returns the line strip draw mode.
  31072. */
  31073. get: function () {
  31074. return Material._LineStripDrawMode;
  31075. },
  31076. enumerable: true,
  31077. configurable: true
  31078. });
  31079. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31080. /**
  31081. * Returns the triangle strip draw mode.
  31082. */
  31083. get: function () {
  31084. return Material._TriangleStripDrawMode;
  31085. },
  31086. enumerable: true,
  31087. configurable: true
  31088. });
  31089. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31090. /**
  31091. * Returns the triangle fan draw mode.
  31092. */
  31093. get: function () {
  31094. return Material._TriangleFanDrawMode;
  31095. },
  31096. enumerable: true,
  31097. configurable: true
  31098. });
  31099. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31100. /**
  31101. * Returns the clock-wise side orientation.
  31102. */
  31103. get: function () {
  31104. return Material._ClockWiseSideOrientation;
  31105. },
  31106. enumerable: true,
  31107. configurable: true
  31108. });
  31109. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31110. /**
  31111. * Returns the counter clock-wise side orientation.
  31112. */
  31113. get: function () {
  31114. return Material._CounterClockWiseSideOrientation;
  31115. },
  31116. enumerable: true,
  31117. configurable: true
  31118. });
  31119. Object.defineProperty(Material, "TextureDirtyFlag", {
  31120. /**
  31121. * Returns the dirty texture flag value.
  31122. */
  31123. get: function () {
  31124. return Material._TextureDirtyFlag;
  31125. },
  31126. enumerable: true,
  31127. configurable: true
  31128. });
  31129. Object.defineProperty(Material, "LightDirtyFlag", {
  31130. /**
  31131. * Returns the dirty light flag value.
  31132. */
  31133. get: function () {
  31134. return Material._LightDirtyFlag;
  31135. },
  31136. enumerable: true,
  31137. configurable: true
  31138. });
  31139. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31140. /**
  31141. * Returns the dirty fresnel flag value.
  31142. */
  31143. get: function () {
  31144. return Material._FresnelDirtyFlag;
  31145. },
  31146. enumerable: true,
  31147. configurable: true
  31148. });
  31149. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31150. /**
  31151. * Returns the dirty attributes flag value.
  31152. */
  31153. get: function () {
  31154. return Material._AttributesDirtyFlag;
  31155. },
  31156. enumerable: true,
  31157. configurable: true
  31158. });
  31159. Object.defineProperty(Material, "MiscDirtyFlag", {
  31160. /**
  31161. * Returns the dirty misc flag value.
  31162. */
  31163. get: function () {
  31164. return Material._MiscDirtyFlag;
  31165. },
  31166. enumerable: true,
  31167. configurable: true
  31168. });
  31169. Object.defineProperty(Material.prototype, "alpha", {
  31170. /**
  31171. * Gets the alpha value of the material.
  31172. */
  31173. get: function () {
  31174. return this._alpha;
  31175. },
  31176. /**
  31177. * Sets the alpha value of the material.
  31178. */
  31179. set: function (value) {
  31180. if (this._alpha === value) {
  31181. return;
  31182. }
  31183. this._alpha = value;
  31184. this.markAsDirty(Material.MiscDirtyFlag);
  31185. },
  31186. enumerable: true,
  31187. configurable: true
  31188. });
  31189. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31190. /**
  31191. * Gets the back-face culling state.
  31192. */
  31193. get: function () {
  31194. return this._backFaceCulling;
  31195. },
  31196. /**
  31197. * Sets the back-face culling state.
  31198. */
  31199. set: function (value) {
  31200. if (this._backFaceCulling === value) {
  31201. return;
  31202. }
  31203. this._backFaceCulling = value;
  31204. this.markAsDirty(Material.TextureDirtyFlag);
  31205. },
  31206. enumerable: true,
  31207. configurable: true
  31208. });
  31209. Object.defineProperty(Material.prototype, "onDispose", {
  31210. /**
  31211. * Called during a dispose event.
  31212. */
  31213. set: function (callback) {
  31214. if (this._onDisposeObserver) {
  31215. this.onDisposeObservable.remove(this._onDisposeObserver);
  31216. }
  31217. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31218. },
  31219. enumerable: true,
  31220. configurable: true
  31221. });
  31222. Object.defineProperty(Material.prototype, "onBind", {
  31223. /**
  31224. * Called during a bind event.
  31225. */
  31226. set: function (callback) {
  31227. if (this._onBindObserver) {
  31228. this.onBindObservable.remove(this._onBindObserver);
  31229. }
  31230. this._onBindObserver = this.onBindObservable.add(callback);
  31231. },
  31232. enumerable: true,
  31233. configurable: true
  31234. });
  31235. Object.defineProperty(Material.prototype, "alphaMode", {
  31236. /**
  31237. * Gets the value of the alpha mode.
  31238. */
  31239. get: function () {
  31240. return this._alphaMode;
  31241. },
  31242. /**
  31243. * Sets the value of the alpha mode.
  31244. */
  31245. set: function (value) {
  31246. if (this._alphaMode === value) {
  31247. return;
  31248. }
  31249. this._alphaMode = value;
  31250. this.markAsDirty(Material.TextureDirtyFlag);
  31251. },
  31252. enumerable: true,
  31253. configurable: true
  31254. });
  31255. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31256. /**
  31257. * Gets the depth pre-pass value.
  31258. */
  31259. get: function () {
  31260. return this._needDepthPrePass;
  31261. },
  31262. /**
  31263. * Sets the need depth pre-pass value.
  31264. */
  31265. set: function (value) {
  31266. if (this._needDepthPrePass === value) {
  31267. return;
  31268. }
  31269. this._needDepthPrePass = value;
  31270. if (this._needDepthPrePass) {
  31271. this.checkReadyOnEveryCall = true;
  31272. }
  31273. },
  31274. enumerable: true,
  31275. configurable: true
  31276. });
  31277. Object.defineProperty(Material.prototype, "fogEnabled", {
  31278. /**
  31279. * Gets the value of the fog enabled state.
  31280. */
  31281. get: function () {
  31282. return this._fogEnabled;
  31283. },
  31284. /**
  31285. * Sets the state for enabling fog.
  31286. */
  31287. set: function (value) {
  31288. if (this._fogEnabled === value) {
  31289. return;
  31290. }
  31291. this._fogEnabled = value;
  31292. this.markAsDirty(Material.MiscDirtyFlag);
  31293. },
  31294. enumerable: true,
  31295. configurable: true
  31296. });
  31297. Object.defineProperty(Material.prototype, "wireframe", {
  31298. /**
  31299. * Gets a value specifying if wireframe mode is enabled.
  31300. */
  31301. get: function () {
  31302. return this._fillMode === Material.WireFrameFillMode;
  31303. },
  31304. /**
  31305. * Sets the state of wireframe mode.
  31306. */
  31307. set: function (value) {
  31308. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31309. },
  31310. enumerable: true,
  31311. configurable: true
  31312. });
  31313. Object.defineProperty(Material.prototype, "pointsCloud", {
  31314. /**
  31315. * Gets the value specifying if point clouds are enabled.
  31316. */
  31317. get: function () {
  31318. return this._fillMode === Material.PointFillMode;
  31319. },
  31320. /**
  31321. * Sets the state of point cloud mode.
  31322. */
  31323. set: function (value) {
  31324. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31325. },
  31326. enumerable: true,
  31327. configurable: true
  31328. });
  31329. Object.defineProperty(Material.prototype, "fillMode", {
  31330. /**
  31331. * Gets the material fill mode.
  31332. */
  31333. get: function () {
  31334. return this._fillMode;
  31335. },
  31336. /**
  31337. * Sets the material fill mode.
  31338. */
  31339. set: function (value) {
  31340. if (this._fillMode === value) {
  31341. return;
  31342. }
  31343. this._fillMode = value;
  31344. this.markAsDirty(Material.MiscDirtyFlag);
  31345. },
  31346. enumerable: true,
  31347. configurable: true
  31348. });
  31349. /**
  31350. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31351. * subclasses should override adding information pertainent to themselves.
  31352. * @returns - String with material information.
  31353. */
  31354. Material.prototype.toString = function (fullDetails) {
  31355. var ret = "Name: " + this.name;
  31356. if (fullDetails) {
  31357. }
  31358. return ret;
  31359. };
  31360. /**
  31361. * Gets the class name of the material.
  31362. * @returns - String with the class name of the material.
  31363. */
  31364. Material.prototype.getClassName = function () {
  31365. return "Material";
  31366. };
  31367. Object.defineProperty(Material.prototype, "isFrozen", {
  31368. /**
  31369. * Specifies if updates for the material been locked.
  31370. */
  31371. get: function () {
  31372. return this.checkReadyOnlyOnce;
  31373. },
  31374. enumerable: true,
  31375. configurable: true
  31376. });
  31377. /**
  31378. * Locks updates for the material.
  31379. */
  31380. Material.prototype.freeze = function () {
  31381. this.checkReadyOnlyOnce = true;
  31382. };
  31383. /**
  31384. * Unlocks updates for the material.
  31385. */
  31386. Material.prototype.unfreeze = function () {
  31387. this.checkReadyOnlyOnce = false;
  31388. };
  31389. /**
  31390. * Specifies if the material is ready to be used.
  31391. * @param mesh - BJS mesh.
  31392. * @param useInstances - Specifies if instances should be used.
  31393. * @returns - Boolean indicating if the material is ready to be used.
  31394. */
  31395. Material.prototype.isReady = function (mesh, useInstances) {
  31396. return true;
  31397. };
  31398. /**
  31399. * Specifies that the submesh is ready to be used.
  31400. * @param mesh - BJS mesh.
  31401. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31402. * @param useInstances - Specifies that instances should be used.
  31403. * @returns - boolean indicating that the submesh is ready or not.
  31404. */
  31405. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31406. return false;
  31407. };
  31408. /**
  31409. * Returns the material effect.
  31410. * @returns - Nullable material effect.
  31411. */
  31412. Material.prototype.getEffect = function () {
  31413. return this._effect;
  31414. };
  31415. /**
  31416. * Returns the BJS scene.
  31417. * @returns - BJS Scene.
  31418. */
  31419. Material.prototype.getScene = function () {
  31420. return this._scene;
  31421. };
  31422. /**
  31423. * Specifies if the material will require alpha blending
  31424. * @returns - Boolean specifying if alpha blending is needed.
  31425. */
  31426. Material.prototype.needAlphaBlending = function () {
  31427. return (this.alpha < 1.0);
  31428. };
  31429. /**
  31430. * Specifies if the mesh will require alpha blending.
  31431. * @param mesh - BJS mesh.
  31432. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31433. */
  31434. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31435. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31436. };
  31437. /**
  31438. * Specifies if this material should be rendered in alpha test mode.
  31439. * @returns - Boolean specifying if an alpha test is needed.
  31440. */
  31441. Material.prototype.needAlphaTesting = function () {
  31442. return false;
  31443. };
  31444. /**
  31445. * Gets the texture used for the alpha test.
  31446. * @returns - Nullable alpha test texture.
  31447. */
  31448. Material.prototype.getAlphaTestTexture = function () {
  31449. return null;
  31450. };
  31451. /**
  31452. * Marks the material to indicate that it needs to be re-calculated.
  31453. */
  31454. Material.prototype.markDirty = function () {
  31455. this._wasPreviouslyReady = false;
  31456. };
  31457. Material.prototype._preBind = function (effect, overrideOrientation) {
  31458. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31459. var engine = this._scene.getEngine();
  31460. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31461. var reverse = orientation === Material.ClockWiseSideOrientation;
  31462. engine.enableEffect(effect ? effect : this._effect);
  31463. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31464. return reverse;
  31465. };
  31466. /**
  31467. * Binds the material to the mesh.
  31468. * @param world - World transformation matrix.
  31469. * @param mesh - Mesh to bind the material to.
  31470. */
  31471. Material.prototype.bind = function (world, mesh) {
  31472. };
  31473. /**
  31474. * Binds the submesh to the material.
  31475. * @param world - World transformation matrix.
  31476. * @param mesh - Mesh containing the submesh.
  31477. * @param subMesh - Submesh to bind the material to.
  31478. */
  31479. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31480. };
  31481. /**
  31482. * Binds the world matrix to the material.
  31483. * @param world - World transformation matrix.
  31484. */
  31485. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31486. };
  31487. /**
  31488. * Binds the scene's uniform buffer to the effect.
  31489. * @param effect - Effect to bind to the scene uniform buffer.
  31490. * @param sceneUbo - Scene uniform buffer.
  31491. */
  31492. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31493. sceneUbo.bindToEffect(effect, "Scene");
  31494. };
  31495. /**
  31496. * Binds the view matrix to the effect.
  31497. * @param effect - Effect to bind the view matrix to.
  31498. */
  31499. Material.prototype.bindView = function (effect) {
  31500. if (!this._useUBO) {
  31501. effect.setMatrix("view", this.getScene().getViewMatrix());
  31502. }
  31503. else {
  31504. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31505. }
  31506. };
  31507. /**
  31508. * Binds the view projection matrix to the effect.
  31509. * @param effect - Effect to bind the view projection matrix to.
  31510. */
  31511. Material.prototype.bindViewProjection = function (effect) {
  31512. if (!this._useUBO) {
  31513. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31514. }
  31515. else {
  31516. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31517. }
  31518. };
  31519. /**
  31520. * Specifies if material alpha testing should be turned on for the mesh.
  31521. * @param mesh - BJS mesh.
  31522. */
  31523. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31524. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31525. };
  31526. /**
  31527. * Processes to execute after binding the material to a mesh.
  31528. * @param mesh - BJS mesh.
  31529. */
  31530. Material.prototype._afterBind = function (mesh) {
  31531. this._scene._cachedMaterial = this;
  31532. if (mesh) {
  31533. this._scene._cachedVisibility = mesh.visibility;
  31534. }
  31535. else {
  31536. this._scene._cachedVisibility = 1;
  31537. }
  31538. if (mesh) {
  31539. this.onBindObservable.notifyObservers(mesh);
  31540. }
  31541. if (this.disableDepthWrite) {
  31542. var engine = this._scene.getEngine();
  31543. this._cachedDepthWriteState = engine.getDepthWrite();
  31544. engine.setDepthWrite(false);
  31545. }
  31546. };
  31547. /**
  31548. * Unbinds the material from the mesh.
  31549. */
  31550. Material.prototype.unbind = function () {
  31551. this.onUnBindObservable.notifyObservers(this);
  31552. if (this.disableDepthWrite) {
  31553. var engine = this._scene.getEngine();
  31554. engine.setDepthWrite(this._cachedDepthWriteState);
  31555. }
  31556. };
  31557. /**
  31558. * Gets the active textures from the material.
  31559. * @returns - Array of textures.
  31560. */
  31561. Material.prototype.getActiveTextures = function () {
  31562. return [];
  31563. };
  31564. /**
  31565. * Specifies if the material uses a texture.
  31566. * @param texture - Texture to check against the material.
  31567. * @returns - Boolean specifying if the material uses the texture.
  31568. */
  31569. Material.prototype.hasTexture = function (texture) {
  31570. return false;
  31571. };
  31572. /**
  31573. * Makes a duplicate of the material, and gives it a new name.
  31574. * @param name - Name to call the duplicated material.
  31575. * @returns - Nullable cloned material
  31576. */
  31577. Material.prototype.clone = function (name) {
  31578. return null;
  31579. };
  31580. /**
  31581. * Gets the meshes bound to the material.
  31582. * @returns - Array of meshes bound to the material.
  31583. */
  31584. Material.prototype.getBindedMeshes = function () {
  31585. var result = new Array();
  31586. for (var index = 0; index < this._scene.meshes.length; index++) {
  31587. var mesh = this._scene.meshes[index];
  31588. if (mesh.material === this) {
  31589. result.push(mesh);
  31590. }
  31591. }
  31592. return result;
  31593. };
  31594. /**
  31595. * Force shader compilation
  31596. * @param mesh - BJS mesh.
  31597. * @param onCompiled - function to execute once the material is compiled.
  31598. * @param options - options to pass to this function.
  31599. */
  31600. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31601. var _this = this;
  31602. var localOptions = __assign({ clipPlane: false }, options);
  31603. var subMesh = new BABYLON.BaseSubMesh();
  31604. var scene = this.getScene();
  31605. var checkReady = function () {
  31606. if (!_this._scene || !_this._scene.getEngine()) {
  31607. return;
  31608. }
  31609. if (subMesh._materialDefines) {
  31610. subMesh._materialDefines._renderId = -1;
  31611. }
  31612. var clipPlaneState = scene.clipPlane;
  31613. if (localOptions.clipPlane) {
  31614. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31615. }
  31616. if (_this.storeEffectOnSubMeshes) {
  31617. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31618. if (onCompiled) {
  31619. onCompiled(_this);
  31620. }
  31621. }
  31622. else {
  31623. setTimeout(checkReady, 16);
  31624. }
  31625. }
  31626. else {
  31627. if (_this.isReady(mesh)) {
  31628. if (onCompiled) {
  31629. onCompiled(_this);
  31630. }
  31631. }
  31632. else {
  31633. setTimeout(checkReady, 16);
  31634. }
  31635. }
  31636. if (localOptions.clipPlane) {
  31637. scene.clipPlane = clipPlaneState;
  31638. }
  31639. };
  31640. checkReady();
  31641. };
  31642. /**
  31643. * Force shader compilation.
  31644. * @param mesh The mesh that will use this material
  31645. * @param options Additional options for compiling the shaders
  31646. * @returns A promise that resolves when the compilation completes
  31647. */
  31648. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31649. var _this = this;
  31650. return new Promise(function (resolve) {
  31651. _this.forceCompilation(mesh, function () {
  31652. resolve();
  31653. }, options);
  31654. });
  31655. };
  31656. /**
  31657. * Marks a define in the material to indicate that it needs to be re-computed.
  31658. * @param flag - Material define flag.
  31659. */
  31660. Material.prototype.markAsDirty = function (flag) {
  31661. if (flag & Material.TextureDirtyFlag) {
  31662. this._markAllSubMeshesAsTexturesDirty();
  31663. }
  31664. if (flag & Material.LightDirtyFlag) {
  31665. this._markAllSubMeshesAsLightsDirty();
  31666. }
  31667. if (flag & Material.FresnelDirtyFlag) {
  31668. this._markAllSubMeshesAsFresnelDirty();
  31669. }
  31670. if (flag & Material.AttributesDirtyFlag) {
  31671. this._markAllSubMeshesAsAttributesDirty();
  31672. }
  31673. if (flag & Material.MiscDirtyFlag) {
  31674. this._markAllSubMeshesAsMiscDirty();
  31675. }
  31676. this.getScene().resetCachedMaterial();
  31677. };
  31678. /**
  31679. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31680. * @param func - function which checks material defines against the submeshes.
  31681. */
  31682. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31683. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31684. var mesh = _a[_i];
  31685. if (!mesh.subMeshes) {
  31686. continue;
  31687. }
  31688. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31689. var subMesh = _c[_b];
  31690. if (subMesh.getMaterial() !== this) {
  31691. continue;
  31692. }
  31693. if (!subMesh._materialDefines) {
  31694. continue;
  31695. }
  31696. func(subMesh._materialDefines);
  31697. }
  31698. }
  31699. };
  31700. /**
  31701. * Indicates that image processing needs to be re-calculated for all submeshes.
  31702. */
  31703. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31704. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31705. };
  31706. /**
  31707. * Indicates that textures need to be re-calculated for all submeshes.
  31708. */
  31709. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31710. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31711. };
  31712. /**
  31713. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31714. */
  31715. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31716. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31717. };
  31718. /**
  31719. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31720. */
  31721. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31722. this._markAllSubMeshesAsDirty(function (defines) {
  31723. defines.markAsFresnelDirty();
  31724. defines.markAsMiscDirty();
  31725. });
  31726. };
  31727. /**
  31728. * Indicates that lights need to be re-calculated for all submeshes.
  31729. */
  31730. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31731. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31732. };
  31733. /**
  31734. * Indicates that attributes need to be re-calculated for all submeshes.
  31735. */
  31736. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31737. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31738. };
  31739. /**
  31740. * Indicates that misc needs to be re-calculated for all submeshes.
  31741. */
  31742. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31743. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31744. };
  31745. /**
  31746. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31747. */
  31748. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31749. this._markAllSubMeshesAsDirty(function (defines) {
  31750. defines.markAsTexturesDirty();
  31751. defines.markAsMiscDirty();
  31752. });
  31753. };
  31754. /**
  31755. * Disposes the material.
  31756. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31757. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31758. */
  31759. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31760. // Animations
  31761. this.getScene().stopAnimation(this);
  31762. this.getScene().freeProcessedMaterials();
  31763. // Remove from scene
  31764. var index = this._scene.materials.indexOf(this);
  31765. if (index >= 0) {
  31766. this._scene.materials.splice(index, 1);
  31767. }
  31768. // Remove from meshes
  31769. for (index = 0; index < this._scene.meshes.length; index++) {
  31770. var mesh = this._scene.meshes[index];
  31771. if (mesh.material === this) {
  31772. mesh.material = null;
  31773. if (mesh.geometry) {
  31774. var geometry = (mesh.geometry);
  31775. if (this.storeEffectOnSubMeshes) {
  31776. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31777. var subMesh = _a[_i];
  31778. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31779. if (forceDisposeEffect && subMesh._materialEffect) {
  31780. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31781. }
  31782. }
  31783. }
  31784. else {
  31785. geometry._releaseVertexArrayObject(this._effect);
  31786. }
  31787. }
  31788. }
  31789. }
  31790. this._uniformBuffer.dispose();
  31791. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31792. if (forceDisposeEffect && this._effect) {
  31793. if (!this.storeEffectOnSubMeshes) {
  31794. this._scene.getEngine()._releaseEffect(this._effect);
  31795. }
  31796. this._effect = null;
  31797. }
  31798. // Callback
  31799. this.onDisposeObservable.notifyObservers(this);
  31800. this.onDisposeObservable.clear();
  31801. this.onBindObservable.clear();
  31802. this.onUnBindObservable.clear();
  31803. };
  31804. /**
  31805. * Serializes this material.
  31806. * @returns - serialized material object.
  31807. */
  31808. Material.prototype.serialize = function () {
  31809. return BABYLON.SerializationHelper.Serialize(this);
  31810. };
  31811. /**
  31812. * Creates a MultiMaterial from parse MultiMaterial data.
  31813. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31814. * @param scene - BJS scene.
  31815. * @returns - MultiMaterial.
  31816. */
  31817. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31818. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31819. multiMaterial.id = parsedMultiMaterial.id;
  31820. if (BABYLON.Tags) {
  31821. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31822. }
  31823. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31824. var subMatId = parsedMultiMaterial.materials[matIndex];
  31825. if (subMatId) {
  31826. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31827. }
  31828. else {
  31829. multiMaterial.subMaterials.push(null);
  31830. }
  31831. }
  31832. return multiMaterial;
  31833. };
  31834. /**
  31835. * Creates a material from parsed material data.
  31836. * @param parsedMaterial - Parsed material data.
  31837. * @param scene - BJS scene.
  31838. * @param rootUrl - Root URL containing the material information.
  31839. * @returns - Parsed material.
  31840. */
  31841. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31842. if (!parsedMaterial.customType) {
  31843. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31844. }
  31845. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31846. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31847. if (!BABYLON.LegacyPBRMaterial) {
  31848. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31849. return;
  31850. }
  31851. }
  31852. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31853. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31854. ;
  31855. };
  31856. // Triangle views
  31857. Material._TriangleFillMode = 0;
  31858. Material._WireFrameFillMode = 1;
  31859. Material._PointFillMode = 2;
  31860. // Draw modes
  31861. Material._PointListDrawMode = 3;
  31862. Material._LineListDrawMode = 4;
  31863. Material._LineLoopDrawMode = 5;
  31864. Material._LineStripDrawMode = 6;
  31865. Material._TriangleStripDrawMode = 7;
  31866. Material._TriangleFanDrawMode = 8;
  31867. /**
  31868. * Stores the clock-wise side orientation.
  31869. */
  31870. Material._ClockWiseSideOrientation = 0;
  31871. /**
  31872. * Stores the counter clock-wise side orientation.
  31873. */
  31874. Material._CounterClockWiseSideOrientation = 1;
  31875. /**
  31876. * The dirty texture flag value.
  31877. */
  31878. Material._TextureDirtyFlag = 1;
  31879. /**
  31880. * The dirty light flag value.
  31881. */
  31882. Material._LightDirtyFlag = 2;
  31883. /**
  31884. * The dirty fresnel flag value.
  31885. */
  31886. Material._FresnelDirtyFlag = 4;
  31887. /**
  31888. * The dirty attribute flag value.
  31889. */
  31890. Material._AttributesDirtyFlag = 8;
  31891. /**
  31892. * The dirty misc flag value.
  31893. */
  31894. Material._MiscDirtyFlag = 16;
  31895. __decorate([
  31896. BABYLON.serialize()
  31897. ], Material.prototype, "id", void 0);
  31898. __decorate([
  31899. BABYLON.serialize()
  31900. ], Material.prototype, "name", void 0);
  31901. __decorate([
  31902. BABYLON.serialize()
  31903. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31904. __decorate([
  31905. BABYLON.serialize()
  31906. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31907. __decorate([
  31908. BABYLON.serialize()
  31909. ], Material.prototype, "state", void 0);
  31910. __decorate([
  31911. BABYLON.serialize("alpha")
  31912. ], Material.prototype, "_alpha", void 0);
  31913. __decorate([
  31914. BABYLON.serialize("backFaceCulling")
  31915. ], Material.prototype, "_backFaceCulling", void 0);
  31916. __decorate([
  31917. BABYLON.serialize()
  31918. ], Material.prototype, "sideOrientation", void 0);
  31919. __decorate([
  31920. BABYLON.serialize("alphaMode")
  31921. ], Material.prototype, "_alphaMode", void 0);
  31922. __decorate([
  31923. BABYLON.serialize()
  31924. ], Material.prototype, "_needDepthPrePass", void 0);
  31925. __decorate([
  31926. BABYLON.serialize()
  31927. ], Material.prototype, "disableDepthWrite", void 0);
  31928. __decorate([
  31929. BABYLON.serialize()
  31930. ], Material.prototype, "forceDepthWrite", void 0);
  31931. __decorate([
  31932. BABYLON.serialize()
  31933. ], Material.prototype, "separateCullingPass", void 0);
  31934. __decorate([
  31935. BABYLON.serialize("fogEnabled")
  31936. ], Material.prototype, "_fogEnabled", void 0);
  31937. __decorate([
  31938. BABYLON.serialize()
  31939. ], Material.prototype, "pointSize", void 0);
  31940. __decorate([
  31941. BABYLON.serialize()
  31942. ], Material.prototype, "zOffset", void 0);
  31943. __decorate([
  31944. BABYLON.serialize()
  31945. ], Material.prototype, "wireframe", null);
  31946. __decorate([
  31947. BABYLON.serialize()
  31948. ], Material.prototype, "pointsCloud", null);
  31949. __decorate([
  31950. BABYLON.serialize()
  31951. ], Material.prototype, "fillMode", null);
  31952. return Material;
  31953. }());
  31954. BABYLON.Material = Material;
  31955. })(BABYLON || (BABYLON = {}));
  31956. //# sourceMappingURL=babylon.material.js.map
  31957. var BABYLON;
  31958. (function (BABYLON) {
  31959. var UniformBuffer = /** @class */ (function () {
  31960. /**
  31961. * Uniform buffer objects.
  31962. *
  31963. * Handles blocks of uniform on the GPU.
  31964. *
  31965. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31966. *
  31967. * For more information, please refer to :
  31968. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31969. */
  31970. function UniformBuffer(engine, data, dynamic) {
  31971. this._engine = engine;
  31972. this._noUBO = !engine.supportsUniformBuffers;
  31973. this._dynamic = dynamic;
  31974. this._data = data || [];
  31975. this._uniformLocations = {};
  31976. this._uniformSizes = {};
  31977. this._uniformLocationPointer = 0;
  31978. this._needSync = false;
  31979. if (this._noUBO) {
  31980. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31981. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31982. this.updateFloat = this._updateFloatForEffect;
  31983. this.updateFloat2 = this._updateFloat2ForEffect;
  31984. this.updateFloat3 = this._updateFloat3ForEffect;
  31985. this.updateFloat4 = this._updateFloat4ForEffect;
  31986. this.updateMatrix = this._updateMatrixForEffect;
  31987. this.updateVector3 = this._updateVector3ForEffect;
  31988. this.updateVector4 = this._updateVector4ForEffect;
  31989. this.updateColor3 = this._updateColor3ForEffect;
  31990. this.updateColor4 = this._updateColor4ForEffect;
  31991. }
  31992. else {
  31993. this._engine._uniformBuffers.push(this);
  31994. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31995. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31996. this.updateFloat = this._updateFloatForUniform;
  31997. this.updateFloat2 = this._updateFloat2ForUniform;
  31998. this.updateFloat3 = this._updateFloat3ForUniform;
  31999. this.updateFloat4 = this._updateFloat4ForUniform;
  32000. this.updateMatrix = this._updateMatrixForUniform;
  32001. this.updateVector3 = this._updateVector3ForUniform;
  32002. this.updateVector4 = this._updateVector4ForUniform;
  32003. this.updateColor3 = this._updateColor3ForUniform;
  32004. this.updateColor4 = this._updateColor4ForUniform;
  32005. }
  32006. }
  32007. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32008. // Properties
  32009. /**
  32010. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32011. * or just falling back on setUniformXXX calls.
  32012. */
  32013. get: function () {
  32014. return !this._noUBO;
  32015. },
  32016. enumerable: true,
  32017. configurable: true
  32018. });
  32019. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32020. /**
  32021. * Indicates if the WebGL underlying uniform buffer is in sync
  32022. * with the javascript cache data.
  32023. */
  32024. get: function () {
  32025. return !this._needSync;
  32026. },
  32027. enumerable: true,
  32028. configurable: true
  32029. });
  32030. /**
  32031. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32032. * Also, a dynamic UniformBuffer will disable cache verification and always
  32033. * update the underlying WebGL uniform buffer to the GPU.
  32034. */
  32035. UniformBuffer.prototype.isDynamic = function () {
  32036. return this._dynamic !== undefined;
  32037. };
  32038. /**
  32039. * The data cache on JS side.
  32040. */
  32041. UniformBuffer.prototype.getData = function () {
  32042. return this._bufferData;
  32043. };
  32044. /**
  32045. * The underlying WebGL Uniform buffer.
  32046. */
  32047. UniformBuffer.prototype.getBuffer = function () {
  32048. return this._buffer;
  32049. };
  32050. /**
  32051. * std140 layout specifies how to align data within an UBO structure.
  32052. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32053. * for specs.
  32054. */
  32055. UniformBuffer.prototype._fillAlignment = function (size) {
  32056. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32057. // and 4x4 matrices
  32058. // TODO : change if other types are used
  32059. var alignment;
  32060. if (size <= 2) {
  32061. alignment = size;
  32062. }
  32063. else {
  32064. alignment = 4;
  32065. }
  32066. if ((this._uniformLocationPointer % alignment) !== 0) {
  32067. var oldPointer = this._uniformLocationPointer;
  32068. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32069. var diff = this._uniformLocationPointer - oldPointer;
  32070. for (var i = 0; i < diff; i++) {
  32071. this._data.push(0);
  32072. }
  32073. }
  32074. };
  32075. /**
  32076. * Adds an uniform in the buffer.
  32077. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32078. * for the layout to be correct !
  32079. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32080. * @param {number|number[]} size Data size, or data directly.
  32081. */
  32082. UniformBuffer.prototype.addUniform = function (name, size) {
  32083. if (this._noUBO) {
  32084. return;
  32085. }
  32086. if (this._uniformLocations[name] !== undefined) {
  32087. // Already existing uniform
  32088. return;
  32089. }
  32090. // This function must be called in the order of the shader layout !
  32091. // size can be the size of the uniform, or data directly
  32092. var data;
  32093. if (size instanceof Array) {
  32094. data = size;
  32095. size = data.length;
  32096. }
  32097. else {
  32098. size = size;
  32099. data = [];
  32100. // Fill with zeros
  32101. for (var i = 0; i < size; i++) {
  32102. data.push(0);
  32103. }
  32104. }
  32105. this._fillAlignment(size);
  32106. this._uniformSizes[name] = size;
  32107. this._uniformLocations[name] = this._uniformLocationPointer;
  32108. this._uniformLocationPointer += size;
  32109. for (var i = 0; i < size; i++) {
  32110. this._data.push(data[i]);
  32111. }
  32112. this._needSync = true;
  32113. };
  32114. /**
  32115. * Wrapper for addUniform.
  32116. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32117. * @param {Matrix} mat A 4x4 matrix.
  32118. */
  32119. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32120. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32121. };
  32122. /**
  32123. * Wrapper for addUniform.
  32124. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32125. * @param {number} x
  32126. * @param {number} y
  32127. */
  32128. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32129. var temp = [x, y];
  32130. this.addUniform(name, temp);
  32131. };
  32132. /**
  32133. * Wrapper for addUniform.
  32134. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32135. * @param {number} x
  32136. * @param {number} y
  32137. * @param {number} z
  32138. */
  32139. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32140. var temp = [x, y, z];
  32141. this.addUniform(name, temp);
  32142. };
  32143. /**
  32144. * Wrapper for addUniform.
  32145. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32146. * @param {Color3} color
  32147. */
  32148. UniformBuffer.prototype.addColor3 = function (name, color) {
  32149. var temp = new Array();
  32150. color.toArray(temp);
  32151. this.addUniform(name, temp);
  32152. };
  32153. /**
  32154. * Wrapper for addUniform.
  32155. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32156. * @param {Color3} color
  32157. * @param {number} alpha
  32158. */
  32159. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32160. var temp = new Array();
  32161. color.toArray(temp);
  32162. temp.push(alpha);
  32163. this.addUniform(name, temp);
  32164. };
  32165. /**
  32166. * Wrapper for addUniform.
  32167. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32168. * @param {Vector3} vector
  32169. */
  32170. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32171. var temp = new Array();
  32172. vector.toArray(temp);
  32173. this.addUniform(name, temp);
  32174. };
  32175. /**
  32176. * Wrapper for addUniform.
  32177. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32178. */
  32179. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32180. this.addUniform(name, 12);
  32181. };
  32182. /**
  32183. * Wrapper for addUniform.
  32184. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32185. */
  32186. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32187. this.addUniform(name, 8);
  32188. };
  32189. /**
  32190. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32191. */
  32192. UniformBuffer.prototype.create = function () {
  32193. if (this._noUBO) {
  32194. return;
  32195. }
  32196. if (this._buffer) {
  32197. return; // nothing to do
  32198. }
  32199. // See spec, alignment must be filled as a vec4
  32200. this._fillAlignment(4);
  32201. this._bufferData = new Float32Array(this._data);
  32202. this._rebuild();
  32203. this._needSync = true;
  32204. };
  32205. UniformBuffer.prototype._rebuild = function () {
  32206. if (this._noUBO) {
  32207. return;
  32208. }
  32209. if (this._dynamic) {
  32210. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32211. }
  32212. else {
  32213. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32214. }
  32215. };
  32216. /**
  32217. * Updates the WebGL Uniform Buffer on the GPU.
  32218. * If the `dynamic` flag is set to true, no cache comparison is done.
  32219. * Otherwise, the buffer will be updated only if the cache differs.
  32220. */
  32221. UniformBuffer.prototype.update = function () {
  32222. if (!this._buffer) {
  32223. this.create();
  32224. return;
  32225. }
  32226. if (!this._dynamic && !this._needSync) {
  32227. return;
  32228. }
  32229. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32230. this._needSync = false;
  32231. };
  32232. /**
  32233. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32234. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32235. * @param {number[]|Float32Array} data Flattened data
  32236. * @param {number} size Size of the data.
  32237. */
  32238. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32239. var location = this._uniformLocations[uniformName];
  32240. if (location === undefined) {
  32241. if (this._buffer) {
  32242. // Cannot add an uniform if the buffer is already created
  32243. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32244. return;
  32245. }
  32246. this.addUniform(uniformName, size);
  32247. location = this._uniformLocations[uniformName];
  32248. }
  32249. if (!this._buffer) {
  32250. this.create();
  32251. }
  32252. if (!this._dynamic) {
  32253. // Cache for static uniform buffers
  32254. var changed = false;
  32255. for (var i = 0; i < size; i++) {
  32256. if (this._bufferData[location + i] !== data[i]) {
  32257. changed = true;
  32258. this._bufferData[location + i] = data[i];
  32259. }
  32260. }
  32261. this._needSync = this._needSync || changed;
  32262. }
  32263. else {
  32264. // No cache for dynamic
  32265. for (var i = 0; i < size; i++) {
  32266. this._bufferData[location + i] = data[i];
  32267. }
  32268. }
  32269. };
  32270. // Update methods
  32271. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32272. // To match std140, matrix must be realigned
  32273. for (var i = 0; i < 3; i++) {
  32274. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32275. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32276. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32277. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32278. }
  32279. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32280. };
  32281. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32282. this._currentEffect.setMatrix3x3(name, matrix);
  32283. };
  32284. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32285. this._currentEffect.setMatrix2x2(name, matrix);
  32286. };
  32287. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32288. // To match std140, matrix must be realigned
  32289. for (var i = 0; i < 2; i++) {
  32290. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32291. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32292. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32293. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32294. }
  32295. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32296. };
  32297. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32298. this._currentEffect.setFloat(name, x);
  32299. };
  32300. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32301. UniformBuffer._tempBuffer[0] = x;
  32302. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32303. };
  32304. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32305. if (suffix === void 0) { suffix = ""; }
  32306. this._currentEffect.setFloat2(name + suffix, x, y);
  32307. };
  32308. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32309. if (suffix === void 0) { suffix = ""; }
  32310. UniformBuffer._tempBuffer[0] = x;
  32311. UniformBuffer._tempBuffer[1] = y;
  32312. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32313. };
  32314. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32315. if (suffix === void 0) { suffix = ""; }
  32316. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32317. };
  32318. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32319. if (suffix === void 0) { suffix = ""; }
  32320. UniformBuffer._tempBuffer[0] = x;
  32321. UniformBuffer._tempBuffer[1] = y;
  32322. UniformBuffer._tempBuffer[2] = z;
  32323. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32324. };
  32325. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32326. if (suffix === void 0) { suffix = ""; }
  32327. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32328. };
  32329. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32330. if (suffix === void 0) { suffix = ""; }
  32331. UniformBuffer._tempBuffer[0] = x;
  32332. UniformBuffer._tempBuffer[1] = y;
  32333. UniformBuffer._tempBuffer[2] = z;
  32334. UniformBuffer._tempBuffer[3] = w;
  32335. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32336. };
  32337. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32338. this._currentEffect.setMatrix(name, mat);
  32339. };
  32340. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32341. this.updateUniform(name, mat.toArray(), 16);
  32342. };
  32343. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32344. this._currentEffect.setVector3(name, vector);
  32345. };
  32346. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32347. vector.toArray(UniformBuffer._tempBuffer);
  32348. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32349. };
  32350. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32351. this._currentEffect.setVector4(name, vector);
  32352. };
  32353. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32354. vector.toArray(UniformBuffer._tempBuffer);
  32355. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32356. };
  32357. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32358. if (suffix === void 0) { suffix = ""; }
  32359. this._currentEffect.setColor3(name + suffix, color);
  32360. };
  32361. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32362. if (suffix === void 0) { suffix = ""; }
  32363. color.toArray(UniformBuffer._tempBuffer);
  32364. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32365. };
  32366. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32367. if (suffix === void 0) { suffix = ""; }
  32368. this._currentEffect.setColor4(name + suffix, color, alpha);
  32369. };
  32370. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32371. if (suffix === void 0) { suffix = ""; }
  32372. color.toArray(UniformBuffer._tempBuffer);
  32373. UniformBuffer._tempBuffer[3] = alpha;
  32374. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32375. };
  32376. /**
  32377. * Sets a sampler uniform on the effect.
  32378. * @param {string} name Name of the sampler.
  32379. * @param {Texture} texture
  32380. */
  32381. UniformBuffer.prototype.setTexture = function (name, texture) {
  32382. this._currentEffect.setTexture(name, texture);
  32383. };
  32384. /**
  32385. * Directly updates the value of the uniform in the cache AND on the GPU.
  32386. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32387. * @param {number[]|Float32Array} data Flattened data
  32388. */
  32389. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32390. this.updateUniform(uniformName, data, data.length);
  32391. this.update();
  32392. };
  32393. /**
  32394. * Binds this uniform buffer to an effect.
  32395. * @param {Effect} effect
  32396. * @param {string} name Name of the uniform block in the shader.
  32397. */
  32398. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32399. this._currentEffect = effect;
  32400. if (this._noUBO || !this._buffer) {
  32401. return;
  32402. }
  32403. effect.bindUniformBuffer(this._buffer, name);
  32404. };
  32405. /**
  32406. * Disposes the uniform buffer.
  32407. */
  32408. UniformBuffer.prototype.dispose = function () {
  32409. if (this._noUBO) {
  32410. return;
  32411. }
  32412. var index = this._engine._uniformBuffers.indexOf(this);
  32413. if (index !== -1) {
  32414. this._engine._uniformBuffers.splice(index, 1);
  32415. }
  32416. if (!this._buffer) {
  32417. return;
  32418. }
  32419. if (this._engine._releaseBuffer(this._buffer)) {
  32420. this._buffer = null;
  32421. }
  32422. };
  32423. // Pool for avoiding memory leaks
  32424. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32425. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32426. return UniformBuffer;
  32427. }());
  32428. BABYLON.UniformBuffer = UniformBuffer;
  32429. })(BABYLON || (BABYLON = {}));
  32430. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32431. var BABYLON;
  32432. (function (BABYLON) {
  32433. var VertexData = /** @class */ (function () {
  32434. function VertexData() {
  32435. }
  32436. VertexData.prototype.set = function (data, kind) {
  32437. switch (kind) {
  32438. case BABYLON.VertexBuffer.PositionKind:
  32439. this.positions = data;
  32440. break;
  32441. case BABYLON.VertexBuffer.NormalKind:
  32442. this.normals = data;
  32443. break;
  32444. case BABYLON.VertexBuffer.TangentKind:
  32445. this.tangents = data;
  32446. break;
  32447. case BABYLON.VertexBuffer.UVKind:
  32448. this.uvs = data;
  32449. break;
  32450. case BABYLON.VertexBuffer.UV2Kind:
  32451. this.uvs2 = data;
  32452. break;
  32453. case BABYLON.VertexBuffer.UV3Kind:
  32454. this.uvs3 = data;
  32455. break;
  32456. case BABYLON.VertexBuffer.UV4Kind:
  32457. this.uvs4 = data;
  32458. break;
  32459. case BABYLON.VertexBuffer.UV5Kind:
  32460. this.uvs5 = data;
  32461. break;
  32462. case BABYLON.VertexBuffer.UV6Kind:
  32463. this.uvs6 = data;
  32464. break;
  32465. case BABYLON.VertexBuffer.ColorKind:
  32466. this.colors = data;
  32467. break;
  32468. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32469. this.matricesIndices = data;
  32470. break;
  32471. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32472. this.matricesWeights = data;
  32473. break;
  32474. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32475. this.matricesIndicesExtra = data;
  32476. break;
  32477. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32478. this.matricesWeightsExtra = data;
  32479. break;
  32480. }
  32481. };
  32482. /**
  32483. * Associates the vertexData to the passed Mesh.
  32484. * Sets it as updatable or not (default `false`).
  32485. * Returns the VertexData.
  32486. */
  32487. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32488. this._applyTo(mesh, updatable);
  32489. return this;
  32490. };
  32491. /**
  32492. * Associates the vertexData to the passed Geometry.
  32493. * Sets it as updatable or not (default `false`).
  32494. * Returns the VertexData.
  32495. */
  32496. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32497. this._applyTo(geometry, updatable);
  32498. return this;
  32499. };
  32500. /**
  32501. * Updates the associated mesh.
  32502. * Returns the VertexData.
  32503. */
  32504. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32505. this._update(mesh);
  32506. return this;
  32507. };
  32508. /**
  32509. * Updates the associated geometry.
  32510. * Returns the VertexData.
  32511. */
  32512. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32513. this._update(geometry);
  32514. return this;
  32515. };
  32516. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32517. if (updatable === void 0) { updatable = false; }
  32518. if (this.positions) {
  32519. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32520. }
  32521. if (this.normals) {
  32522. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32523. }
  32524. if (this.tangents) {
  32525. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32526. }
  32527. if (this.uvs) {
  32528. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32529. }
  32530. if (this.uvs2) {
  32531. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32532. }
  32533. if (this.uvs3) {
  32534. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32535. }
  32536. if (this.uvs4) {
  32537. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32538. }
  32539. if (this.uvs5) {
  32540. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32541. }
  32542. if (this.uvs6) {
  32543. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32544. }
  32545. if (this.colors) {
  32546. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32547. }
  32548. if (this.matricesIndices) {
  32549. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32550. }
  32551. if (this.matricesWeights) {
  32552. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32553. }
  32554. if (this.matricesIndicesExtra) {
  32555. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32556. }
  32557. if (this.matricesWeightsExtra) {
  32558. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32559. }
  32560. if (this.indices) {
  32561. meshOrGeometry.setIndices(this.indices, null, updatable);
  32562. }
  32563. return this;
  32564. };
  32565. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32566. if (this.positions) {
  32567. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32568. }
  32569. if (this.normals) {
  32570. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32571. }
  32572. if (this.tangents) {
  32573. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32574. }
  32575. if (this.uvs) {
  32576. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32577. }
  32578. if (this.uvs2) {
  32579. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32580. }
  32581. if (this.uvs3) {
  32582. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32583. }
  32584. if (this.uvs4) {
  32585. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32586. }
  32587. if (this.uvs5) {
  32588. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32589. }
  32590. if (this.uvs6) {
  32591. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32592. }
  32593. if (this.colors) {
  32594. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32595. }
  32596. if (this.matricesIndices) {
  32597. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32598. }
  32599. if (this.matricesWeights) {
  32600. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32601. }
  32602. if (this.matricesIndicesExtra) {
  32603. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32604. }
  32605. if (this.matricesWeightsExtra) {
  32606. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32607. }
  32608. if (this.indices) {
  32609. meshOrGeometry.setIndices(this.indices, null);
  32610. }
  32611. return this;
  32612. };
  32613. /**
  32614. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32615. * Returns the VertexData.
  32616. */
  32617. VertexData.prototype.transform = function (matrix) {
  32618. var transformed = BABYLON.Vector3.Zero();
  32619. var index;
  32620. if (this.positions) {
  32621. var position = BABYLON.Vector3.Zero();
  32622. for (index = 0; index < this.positions.length; index += 3) {
  32623. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32624. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32625. this.positions[index] = transformed.x;
  32626. this.positions[index + 1] = transformed.y;
  32627. this.positions[index + 2] = transformed.z;
  32628. }
  32629. }
  32630. if (this.normals) {
  32631. var normal = BABYLON.Vector3.Zero();
  32632. for (index = 0; index < this.normals.length; index += 3) {
  32633. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32634. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32635. this.normals[index] = transformed.x;
  32636. this.normals[index + 1] = transformed.y;
  32637. this.normals[index + 2] = transformed.z;
  32638. }
  32639. }
  32640. if (this.tangents) {
  32641. var tangent = BABYLON.Vector4.Zero();
  32642. var tangentTransformed = BABYLON.Vector4.Zero();
  32643. for (index = 0; index < this.tangents.length; index += 4) {
  32644. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32645. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32646. this.tangents[index] = tangentTransformed.x;
  32647. this.tangents[index + 1] = tangentTransformed.y;
  32648. this.tangents[index + 2] = tangentTransformed.z;
  32649. this.tangents[index + 3] = tangentTransformed.w;
  32650. }
  32651. }
  32652. return this;
  32653. };
  32654. /**
  32655. * Merges the passed VertexData into the current one.
  32656. * Returns the modified VertexData.
  32657. */
  32658. VertexData.prototype.merge = function (other) {
  32659. this._validate();
  32660. other._validate();
  32661. if (!this.normals !== !other.normals ||
  32662. !this.tangents !== !other.tangents ||
  32663. !this.uvs !== !other.uvs ||
  32664. !this.uvs2 !== !other.uvs2 ||
  32665. !this.uvs3 !== !other.uvs3 ||
  32666. !this.uvs4 !== !other.uvs4 ||
  32667. !this.uvs5 !== !other.uvs5 ||
  32668. !this.uvs6 !== !other.uvs6 ||
  32669. !this.colors !== !other.colors ||
  32670. !this.matricesIndices !== !other.matricesIndices ||
  32671. !this.matricesWeights !== !other.matricesWeights ||
  32672. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32673. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32674. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32675. }
  32676. if (other.indices) {
  32677. if (!this.indices) {
  32678. this.indices = [];
  32679. }
  32680. var offset = this.positions ? this.positions.length / 3 : 0;
  32681. for (var index = 0; index < other.indices.length; index++) {
  32682. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32683. this.indices.push(other.indices[index] + offset);
  32684. }
  32685. }
  32686. this.positions = this._mergeElement(this.positions, other.positions);
  32687. this.normals = this._mergeElement(this.normals, other.normals);
  32688. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32689. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32690. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32691. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32692. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32693. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32694. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32695. this.colors = this._mergeElement(this.colors, other.colors);
  32696. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32697. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32698. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32699. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32700. return this;
  32701. };
  32702. VertexData.prototype._mergeElement = function (source, other) {
  32703. if (!source) {
  32704. return other;
  32705. }
  32706. if (!other) {
  32707. return source;
  32708. }
  32709. var len = other.length + source.length;
  32710. var isSrcTypedArray = source instanceof Float32Array;
  32711. var isOthTypedArray = other instanceof Float32Array;
  32712. // use non-loop method when the source is Float32Array
  32713. if (isSrcTypedArray) {
  32714. var ret32 = new Float32Array(len);
  32715. ret32.set(source);
  32716. ret32.set(other, source.length);
  32717. return ret32;
  32718. // source is number[], when other is also use concat
  32719. }
  32720. else if (!isOthTypedArray) {
  32721. return source.concat(other);
  32722. // source is a number[], but other is a Float32Array, loop required
  32723. }
  32724. else {
  32725. var ret = source.slice(0); // copy source to a separate array
  32726. for (var i = 0, len = other.length; i < len; i++) {
  32727. ret.push(other[i]);
  32728. }
  32729. return ret;
  32730. }
  32731. };
  32732. VertexData.prototype._validate = function () {
  32733. if (!this.positions) {
  32734. throw new Error("Positions are required");
  32735. }
  32736. var getElementCount = function (kind, values) {
  32737. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32738. if ((values.length % stride) !== 0) {
  32739. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32740. }
  32741. return values.length / stride;
  32742. };
  32743. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32744. var validateElementCount = function (kind, values) {
  32745. var elementCount = getElementCount(kind, values);
  32746. if (elementCount !== positionsElementCount) {
  32747. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32748. }
  32749. };
  32750. if (this.normals)
  32751. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32752. if (this.tangents)
  32753. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32754. if (this.uvs)
  32755. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32756. if (this.uvs2)
  32757. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32758. if (this.uvs3)
  32759. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32760. if (this.uvs4)
  32761. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32762. if (this.uvs5)
  32763. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32764. if (this.uvs6)
  32765. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32766. if (this.colors)
  32767. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32768. if (this.matricesIndices)
  32769. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32770. if (this.matricesWeights)
  32771. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32772. if (this.matricesIndicesExtra)
  32773. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32774. if (this.matricesWeightsExtra)
  32775. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32776. };
  32777. /**
  32778. * Serializes the VertexData.
  32779. * Returns a serialized object.
  32780. */
  32781. VertexData.prototype.serialize = function () {
  32782. var serializationObject = this.serialize();
  32783. if (this.positions) {
  32784. serializationObject.positions = this.positions;
  32785. }
  32786. if (this.normals) {
  32787. serializationObject.normals = this.normals;
  32788. }
  32789. if (this.tangents) {
  32790. serializationObject.tangents = this.tangents;
  32791. }
  32792. if (this.uvs) {
  32793. serializationObject.uvs = this.uvs;
  32794. }
  32795. if (this.uvs2) {
  32796. serializationObject.uvs2 = this.uvs2;
  32797. }
  32798. if (this.uvs3) {
  32799. serializationObject.uvs3 = this.uvs3;
  32800. }
  32801. if (this.uvs4) {
  32802. serializationObject.uvs4 = this.uvs4;
  32803. }
  32804. if (this.uvs5) {
  32805. serializationObject.uvs5 = this.uvs5;
  32806. }
  32807. if (this.uvs6) {
  32808. serializationObject.uvs6 = this.uvs6;
  32809. }
  32810. if (this.colors) {
  32811. serializationObject.colors = this.colors;
  32812. }
  32813. if (this.matricesIndices) {
  32814. serializationObject.matricesIndices = this.matricesIndices;
  32815. serializationObject.matricesIndices._isExpanded = true;
  32816. }
  32817. if (this.matricesWeights) {
  32818. serializationObject.matricesWeights = this.matricesWeights;
  32819. }
  32820. if (this.matricesIndicesExtra) {
  32821. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32822. serializationObject.matricesIndicesExtra._isExpanded = true;
  32823. }
  32824. if (this.matricesWeightsExtra) {
  32825. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32826. }
  32827. serializationObject.indices = this.indices;
  32828. return serializationObject;
  32829. };
  32830. // Statics
  32831. /**
  32832. * Returns the object VertexData associated to the passed mesh.
  32833. */
  32834. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32835. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32836. };
  32837. /**
  32838. * Returns the object VertexData associated to the passed geometry.
  32839. */
  32840. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32841. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32842. };
  32843. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32844. var result = new VertexData();
  32845. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32846. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32847. }
  32848. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32849. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32850. }
  32851. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32852. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32853. }
  32854. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32855. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32856. }
  32857. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32858. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32859. }
  32860. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32861. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32862. }
  32863. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32864. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32865. }
  32866. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32867. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32868. }
  32869. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32870. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32871. }
  32872. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32873. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32874. }
  32875. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32876. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32877. }
  32878. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32879. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32880. }
  32881. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32882. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32883. }
  32884. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32885. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32886. }
  32887. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32888. return result;
  32889. };
  32890. /**
  32891. * Creates the vertexData of the Ribbon.
  32892. */
  32893. VertexData.CreateRibbon = function (options) {
  32894. var pathArray = options.pathArray;
  32895. var closeArray = options.closeArray || false;
  32896. var closePath = options.closePath || false;
  32897. var invertUV = options.invertUV || false;
  32898. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32899. var offset = options.offset || defaultOffset;
  32900. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32901. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32902. var customUV = options.uvs;
  32903. var customColors = options.colors;
  32904. var positions = [];
  32905. var indices = [];
  32906. var normals = [];
  32907. var uvs = [];
  32908. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32909. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32910. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32911. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32912. var minlg; // minimal length among all paths from pathArray
  32913. var lg = []; // array of path lengths : nb of vertex per path
  32914. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32915. var p; // path iterator
  32916. var i; // point iterator
  32917. var j; // point iterator
  32918. // if single path in pathArray
  32919. if (pathArray.length < 2) {
  32920. var ar1 = [];
  32921. var ar2 = [];
  32922. for (i = 0; i < pathArray[0].length - offset; i++) {
  32923. ar1.push(pathArray[0][i]);
  32924. ar2.push(pathArray[0][i + offset]);
  32925. }
  32926. pathArray = [ar1, ar2];
  32927. }
  32928. // positions and horizontal distances (u)
  32929. var idc = 0;
  32930. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32931. var path;
  32932. var l;
  32933. minlg = pathArray[0].length;
  32934. var vectlg;
  32935. var dist;
  32936. for (p = 0; p < pathArray.length; p++) {
  32937. uTotalDistance[p] = 0;
  32938. us[p] = [0];
  32939. path = pathArray[p];
  32940. l = path.length;
  32941. minlg = (minlg < l) ? minlg : l;
  32942. j = 0;
  32943. while (j < l) {
  32944. positions.push(path[j].x, path[j].y, path[j].z);
  32945. if (j > 0) {
  32946. vectlg = path[j].subtract(path[j - 1]).length();
  32947. dist = vectlg + uTotalDistance[p];
  32948. us[p].push(dist);
  32949. uTotalDistance[p] = dist;
  32950. }
  32951. j++;
  32952. }
  32953. if (closePath) {
  32954. j--;
  32955. positions.push(path[0].x, path[0].y, path[0].z);
  32956. vectlg = path[j].subtract(path[0]).length();
  32957. dist = vectlg + uTotalDistance[p];
  32958. us[p].push(dist);
  32959. uTotalDistance[p] = dist;
  32960. }
  32961. lg[p] = l + closePathCorr;
  32962. idx[p] = idc;
  32963. idc += (l + closePathCorr);
  32964. }
  32965. // vertical distances (v)
  32966. var path1;
  32967. var path2;
  32968. var vertex1 = null;
  32969. var vertex2 = null;
  32970. for (i = 0; i < minlg + closePathCorr; i++) {
  32971. vTotalDistance[i] = 0;
  32972. vs[i] = [0];
  32973. for (p = 0; p < pathArray.length - 1; p++) {
  32974. path1 = pathArray[p];
  32975. path2 = pathArray[p + 1];
  32976. if (i === minlg) {
  32977. vertex1 = path1[0];
  32978. vertex2 = path2[0];
  32979. }
  32980. else {
  32981. vertex1 = path1[i];
  32982. vertex2 = path2[i];
  32983. }
  32984. vectlg = vertex2.subtract(vertex1).length();
  32985. dist = vectlg + vTotalDistance[i];
  32986. vs[i].push(dist);
  32987. vTotalDistance[i] = dist;
  32988. }
  32989. if (closeArray && vertex2 && vertex1) {
  32990. path1 = pathArray[p];
  32991. path2 = pathArray[0];
  32992. if (i === minlg) {
  32993. vertex2 = path2[0];
  32994. }
  32995. vectlg = vertex2.subtract(vertex1).length();
  32996. dist = vectlg + vTotalDistance[i];
  32997. vTotalDistance[i] = dist;
  32998. }
  32999. }
  33000. // uvs
  33001. var u;
  33002. var v;
  33003. if (customUV) {
  33004. for (p = 0; p < customUV.length; p++) {
  33005. uvs.push(customUV[p].x, customUV[p].y);
  33006. }
  33007. }
  33008. else {
  33009. for (p = 0; p < pathArray.length; p++) {
  33010. for (i = 0; i < minlg + closePathCorr; i++) {
  33011. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33012. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33013. if (invertUV) {
  33014. uvs.push(v, u);
  33015. }
  33016. else {
  33017. uvs.push(u, v);
  33018. }
  33019. }
  33020. }
  33021. }
  33022. // indices
  33023. p = 0; // path index
  33024. var pi = 0; // positions array index
  33025. var l1 = lg[p] - 1; // path1 length
  33026. var l2 = lg[p + 1] - 1; // path2 length
  33027. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33028. var shft = idx[1] - idx[0]; // shift
  33029. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33030. while (pi <= min && p < path1nb) {
  33031. // 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
  33032. indices.push(pi, pi + shft, pi + 1);
  33033. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33034. pi += 1;
  33035. if (pi === min) {
  33036. p++;
  33037. if (p === lg.length - 1) {
  33038. shft = idx[0] - idx[p];
  33039. l1 = lg[p] - 1;
  33040. l2 = lg[0] - 1;
  33041. }
  33042. else {
  33043. shft = idx[p + 1] - idx[p];
  33044. l1 = lg[p] - 1;
  33045. l2 = lg[p + 1] - 1;
  33046. }
  33047. pi = idx[p];
  33048. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33049. }
  33050. }
  33051. // normals
  33052. VertexData.ComputeNormals(positions, indices, normals);
  33053. if (closePath) {
  33054. var indexFirst = 0;
  33055. var indexLast = 0;
  33056. for (p = 0; p < pathArray.length; p++) {
  33057. indexFirst = idx[p] * 3;
  33058. if (p + 1 < pathArray.length) {
  33059. indexLast = (idx[p + 1] - 1) * 3;
  33060. }
  33061. else {
  33062. indexLast = normals.length - 3;
  33063. }
  33064. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33065. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33066. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33067. normals[indexLast] = normals[indexFirst];
  33068. normals[indexLast + 1] = normals[indexFirst + 1];
  33069. normals[indexLast + 2] = normals[indexFirst + 2];
  33070. }
  33071. }
  33072. // sides
  33073. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33074. // Colors
  33075. var colors = null;
  33076. if (customColors) {
  33077. colors = new Float32Array(customColors.length * 4);
  33078. for (var c = 0; c < customColors.length; c++) {
  33079. colors[c * 4] = customColors[c].r;
  33080. colors[c * 4 + 1] = customColors[c].g;
  33081. colors[c * 4 + 2] = customColors[c].b;
  33082. colors[c * 4 + 3] = customColors[c].a;
  33083. }
  33084. }
  33085. // Result
  33086. var vertexData = new VertexData();
  33087. var positions32 = new Float32Array(positions);
  33088. var normals32 = new Float32Array(normals);
  33089. var uvs32 = new Float32Array(uvs);
  33090. vertexData.indices = indices;
  33091. vertexData.positions = positions32;
  33092. vertexData.normals = normals32;
  33093. vertexData.uvs = uvs32;
  33094. if (colors) {
  33095. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33096. }
  33097. if (closePath) {
  33098. vertexData._idx = idx;
  33099. }
  33100. return vertexData;
  33101. };
  33102. /**
  33103. * Creates the VertexData of the Box.
  33104. */
  33105. VertexData.CreateBox = function (options) {
  33106. var normalsSource = [
  33107. new BABYLON.Vector3(0, 0, 1),
  33108. new BABYLON.Vector3(0, 0, -1),
  33109. new BABYLON.Vector3(1, 0, 0),
  33110. new BABYLON.Vector3(-1, 0, 0),
  33111. new BABYLON.Vector3(0, 1, 0),
  33112. new BABYLON.Vector3(0, -1, 0)
  33113. ];
  33114. var indices = [];
  33115. var positions = [];
  33116. var normals = [];
  33117. var uvs = [];
  33118. var width = options.width || options.size || 1;
  33119. var height = options.height || options.size || 1;
  33120. var depth = options.depth || options.size || 1;
  33121. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33122. var faceUV = options.faceUV || new Array(6);
  33123. var faceColors = options.faceColors;
  33124. var colors = [];
  33125. // default face colors and UV if undefined
  33126. for (var f = 0; f < 6; f++) {
  33127. if (faceUV[f] === undefined) {
  33128. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33129. }
  33130. if (faceColors && faceColors[f] === undefined) {
  33131. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33132. }
  33133. }
  33134. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33135. // Create each face in turn.
  33136. for (var index = 0; index < normalsSource.length; index++) {
  33137. var normal = normalsSource[index];
  33138. // Get two vectors perpendicular to the face normal and to each other.
  33139. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33140. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33141. // Six indices (two triangles) per face.
  33142. var verticesLength = positions.length / 3;
  33143. indices.push(verticesLength);
  33144. indices.push(verticesLength + 1);
  33145. indices.push(verticesLength + 2);
  33146. indices.push(verticesLength);
  33147. indices.push(verticesLength + 2);
  33148. indices.push(verticesLength + 3);
  33149. // Four vertices per face.
  33150. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33151. positions.push(vertex.x, vertex.y, vertex.z);
  33152. normals.push(normal.x, normal.y, normal.z);
  33153. uvs.push(faceUV[index].z, faceUV[index].w);
  33154. if (faceColors) {
  33155. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33156. }
  33157. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33158. positions.push(vertex.x, vertex.y, vertex.z);
  33159. normals.push(normal.x, normal.y, normal.z);
  33160. uvs.push(faceUV[index].x, faceUV[index].w);
  33161. if (faceColors) {
  33162. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33163. }
  33164. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33165. positions.push(vertex.x, vertex.y, vertex.z);
  33166. normals.push(normal.x, normal.y, normal.z);
  33167. uvs.push(faceUV[index].x, faceUV[index].y);
  33168. if (faceColors) {
  33169. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33170. }
  33171. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33172. positions.push(vertex.x, vertex.y, vertex.z);
  33173. normals.push(normal.x, normal.y, normal.z);
  33174. uvs.push(faceUV[index].z, faceUV[index].y);
  33175. if (faceColors) {
  33176. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33177. }
  33178. }
  33179. // sides
  33180. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33181. // Result
  33182. var vertexData = new VertexData();
  33183. vertexData.indices = indices;
  33184. vertexData.positions = positions;
  33185. vertexData.normals = normals;
  33186. vertexData.uvs = uvs;
  33187. if (faceColors) {
  33188. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33189. vertexData.colors = totalColors;
  33190. }
  33191. return vertexData;
  33192. };
  33193. /**
  33194. * Creates the VertexData of the Sphere.
  33195. */
  33196. VertexData.CreateSphere = function (options) {
  33197. var segments = options.segments || 32;
  33198. var diameterX = options.diameterX || options.diameter || 1;
  33199. var diameterY = options.diameterY || options.diameter || 1;
  33200. var diameterZ = options.diameterZ || options.diameter || 1;
  33201. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33202. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33203. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33204. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33205. var totalZRotationSteps = 2 + segments;
  33206. var totalYRotationSteps = 2 * totalZRotationSteps;
  33207. var indices = [];
  33208. var positions = [];
  33209. var normals = [];
  33210. var uvs = [];
  33211. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33212. var normalizedZ = zRotationStep / totalZRotationSteps;
  33213. var angleZ = normalizedZ * Math.PI * slice;
  33214. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33215. var normalizedY = yRotationStep / totalYRotationSteps;
  33216. var angleY = normalizedY * Math.PI * 2 * arc;
  33217. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33218. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33219. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33220. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33221. var vertex = complete.multiply(radius);
  33222. var normal = complete.divide(radius).normalize();
  33223. positions.push(vertex.x, vertex.y, vertex.z);
  33224. normals.push(normal.x, normal.y, normal.z);
  33225. uvs.push(normalizedY, normalizedZ);
  33226. }
  33227. if (zRotationStep > 0) {
  33228. var verticesCount = positions.length / 3;
  33229. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33230. indices.push((firstIndex));
  33231. indices.push((firstIndex + 1));
  33232. indices.push(firstIndex + totalYRotationSteps + 1);
  33233. indices.push((firstIndex + totalYRotationSteps + 1));
  33234. indices.push((firstIndex + 1));
  33235. indices.push((firstIndex + totalYRotationSteps + 2));
  33236. }
  33237. }
  33238. }
  33239. // Sides
  33240. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33241. // Result
  33242. var vertexData = new VertexData();
  33243. vertexData.indices = indices;
  33244. vertexData.positions = positions;
  33245. vertexData.normals = normals;
  33246. vertexData.uvs = uvs;
  33247. return vertexData;
  33248. };
  33249. /**
  33250. * Creates the VertexData of the Cylinder or Cone.
  33251. */
  33252. VertexData.CreateCylinder = function (options) {
  33253. var height = options.height || 2;
  33254. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33255. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33256. var tessellation = options.tessellation || 24;
  33257. var subdivisions = options.subdivisions || 1;
  33258. var hasRings = options.hasRings ? true : false;
  33259. var enclose = options.enclose ? true : false;
  33260. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33261. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33262. var faceUV = options.faceUV || new Array(3);
  33263. var faceColors = options.faceColors;
  33264. // default face colors and UV if undefined
  33265. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33266. var ringNb = (hasRings) ? subdivisions : 1;
  33267. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33268. var f;
  33269. for (f = 0; f < surfaceNb; f++) {
  33270. if (faceColors && faceColors[f] === undefined) {
  33271. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33272. }
  33273. }
  33274. for (f = 0; f < surfaceNb; f++) {
  33275. if (faceUV && faceUV[f] === undefined) {
  33276. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33277. }
  33278. }
  33279. var indices = new Array();
  33280. var positions = new Array();
  33281. var normals = new Array();
  33282. var uvs = new Array();
  33283. var colors = new Array();
  33284. var angle_step = Math.PI * 2 * arc / tessellation;
  33285. var angle;
  33286. var h;
  33287. var radius;
  33288. var tan = (diameterBottom - diameterTop) / 2 / height;
  33289. var ringVertex = BABYLON.Vector3.Zero();
  33290. var ringNormal = BABYLON.Vector3.Zero();
  33291. var ringFirstVertex = BABYLON.Vector3.Zero();
  33292. var ringFirstNormal = BABYLON.Vector3.Zero();
  33293. var quadNormal = BABYLON.Vector3.Zero();
  33294. var Y = BABYLON.Axis.Y;
  33295. // positions, normals, uvs
  33296. var i;
  33297. var j;
  33298. var r;
  33299. var ringIdx = 1;
  33300. var s = 1; // surface index
  33301. var cs = 0;
  33302. var v = 0;
  33303. for (i = 0; i <= subdivisions; i++) {
  33304. h = i / subdivisions;
  33305. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33306. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33307. for (r = 0; r < ringIdx; r++) {
  33308. if (hasRings) {
  33309. s += r;
  33310. }
  33311. if (enclose) {
  33312. s += 2 * r;
  33313. }
  33314. for (j = 0; j <= tessellation; j++) {
  33315. angle = j * angle_step;
  33316. // position
  33317. ringVertex.x = Math.cos(-angle) * radius;
  33318. ringVertex.y = -height / 2 + h * height;
  33319. ringVertex.z = Math.sin(-angle) * radius;
  33320. // normal
  33321. if (diameterTop === 0 && i === subdivisions) {
  33322. // if no top cap, reuse former normals
  33323. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33324. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33325. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33326. }
  33327. else {
  33328. ringNormal.x = ringVertex.x;
  33329. ringNormal.z = ringVertex.z;
  33330. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33331. ringNormal.normalize();
  33332. }
  33333. // keep first ring vertex values for enclose
  33334. if (j === 0) {
  33335. ringFirstVertex.copyFrom(ringVertex);
  33336. ringFirstNormal.copyFrom(ringNormal);
  33337. }
  33338. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33339. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33340. if (hasRings) {
  33341. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33342. }
  33343. else {
  33344. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33345. }
  33346. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33347. if (faceColors) {
  33348. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33349. }
  33350. }
  33351. // if enclose, add four vertices and their dedicated normals
  33352. if (arc !== 1 && enclose) {
  33353. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33354. positions.push(0, ringVertex.y, 0);
  33355. positions.push(0, ringVertex.y, 0);
  33356. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33357. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33358. quadNormal.normalize();
  33359. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33360. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33361. quadNormal.normalize();
  33362. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33363. if (hasRings) {
  33364. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33365. }
  33366. else {
  33367. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33368. }
  33369. uvs.push(faceUV[s + 1].x, v);
  33370. uvs.push(faceUV[s + 1].z, v);
  33371. if (hasRings) {
  33372. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33373. }
  33374. else {
  33375. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33376. }
  33377. uvs.push(faceUV[s + 2].x, v);
  33378. uvs.push(faceUV[s + 2].z, v);
  33379. if (faceColors) {
  33380. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33381. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33382. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33383. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33384. }
  33385. }
  33386. if (cs !== s) {
  33387. cs = s;
  33388. }
  33389. }
  33390. }
  33391. // indices
  33392. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33393. var s;
  33394. i = 0;
  33395. for (s = 0; s < subdivisions; s++) {
  33396. var i0 = 0;
  33397. var i1 = 0;
  33398. var i2 = 0;
  33399. var i3 = 0;
  33400. for (j = 0; j < tessellation; j++) {
  33401. i0 = i * (e + 1) + j;
  33402. i1 = (i + 1) * (e + 1) + j;
  33403. i2 = i * (e + 1) + (j + 1);
  33404. i3 = (i + 1) * (e + 1) + (j + 1);
  33405. indices.push(i0, i1, i2);
  33406. indices.push(i3, i2, i1);
  33407. }
  33408. if (arc !== 1 && enclose) {
  33409. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33410. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33411. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33412. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33413. }
  33414. i = (hasRings) ? (i + 2) : (i + 1);
  33415. }
  33416. // Caps
  33417. var createCylinderCap = function (isTop) {
  33418. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33419. if (radius === 0) {
  33420. return;
  33421. }
  33422. // Cap positions, normals & uvs
  33423. var angle;
  33424. var circleVector;
  33425. var i;
  33426. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33427. var c = null;
  33428. if (faceColors) {
  33429. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33430. }
  33431. // cap center
  33432. var vbase = positions.length / 3;
  33433. var offset = isTop ? height / 2 : -height / 2;
  33434. var center = new BABYLON.Vector3(0, offset, 0);
  33435. positions.push(center.x, center.y, center.z);
  33436. normals.push(0, isTop ? 1 : -1, 0);
  33437. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33438. if (c) {
  33439. colors.push(c.r, c.g, c.b, c.a);
  33440. }
  33441. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33442. for (i = 0; i <= tessellation; i++) {
  33443. angle = Math.PI * 2 * i * arc / tessellation;
  33444. var cos = Math.cos(-angle);
  33445. var sin = Math.sin(-angle);
  33446. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33447. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33448. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33449. normals.push(0, isTop ? 1 : -1, 0);
  33450. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33451. if (c) {
  33452. colors.push(c.r, c.g, c.b, c.a);
  33453. }
  33454. }
  33455. // Cap indices
  33456. for (i = 0; i < tessellation; i++) {
  33457. if (!isTop) {
  33458. indices.push(vbase);
  33459. indices.push(vbase + (i + 1));
  33460. indices.push(vbase + (i + 2));
  33461. }
  33462. else {
  33463. indices.push(vbase);
  33464. indices.push(vbase + (i + 2));
  33465. indices.push(vbase + (i + 1));
  33466. }
  33467. }
  33468. };
  33469. // add caps to geometry
  33470. createCylinderCap(false);
  33471. createCylinderCap(true);
  33472. // Sides
  33473. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33474. var vertexData = new VertexData();
  33475. vertexData.indices = indices;
  33476. vertexData.positions = positions;
  33477. vertexData.normals = normals;
  33478. vertexData.uvs = uvs;
  33479. if (faceColors) {
  33480. vertexData.colors = colors;
  33481. }
  33482. return vertexData;
  33483. };
  33484. /**
  33485. * Creates the VertexData of the Torus.
  33486. */
  33487. VertexData.CreateTorus = function (options) {
  33488. var indices = [];
  33489. var positions = [];
  33490. var normals = [];
  33491. var uvs = [];
  33492. var diameter = options.diameter || 1;
  33493. var thickness = options.thickness || 0.5;
  33494. var tessellation = options.tessellation || 16;
  33495. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33496. var stride = tessellation + 1;
  33497. for (var i = 0; i <= tessellation; i++) {
  33498. var u = i / tessellation;
  33499. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33500. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33501. for (var j = 0; j <= tessellation; j++) {
  33502. var v = 1 - j / tessellation;
  33503. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33504. var dx = Math.cos(innerAngle);
  33505. var dy = Math.sin(innerAngle);
  33506. // Create a vertex.
  33507. var normal = new BABYLON.Vector3(dx, dy, 0);
  33508. var position = normal.scale(thickness / 2);
  33509. var textureCoordinate = new BABYLON.Vector2(u, v);
  33510. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33511. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33512. positions.push(position.x, position.y, position.z);
  33513. normals.push(normal.x, normal.y, normal.z);
  33514. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33515. // And create indices for two triangles.
  33516. var nextI = (i + 1) % stride;
  33517. var nextJ = (j + 1) % stride;
  33518. indices.push(i * stride + j);
  33519. indices.push(i * stride + nextJ);
  33520. indices.push(nextI * stride + j);
  33521. indices.push(i * stride + nextJ);
  33522. indices.push(nextI * stride + nextJ);
  33523. indices.push(nextI * stride + j);
  33524. }
  33525. }
  33526. // Sides
  33527. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33528. // Result
  33529. var vertexData = new VertexData();
  33530. vertexData.indices = indices;
  33531. vertexData.positions = positions;
  33532. vertexData.normals = normals;
  33533. vertexData.uvs = uvs;
  33534. return vertexData;
  33535. };
  33536. /**
  33537. * Creates the VertexData of the LineSystem.
  33538. */
  33539. VertexData.CreateLineSystem = function (options) {
  33540. var indices = [];
  33541. var positions = [];
  33542. var lines = options.lines;
  33543. var colors = options.colors;
  33544. var vertexColors = [];
  33545. var idx = 0;
  33546. for (var l = 0; l < lines.length; l++) {
  33547. var points = lines[l];
  33548. for (var index = 0; index < points.length; index++) {
  33549. positions.push(points[index].x, points[index].y, points[index].z);
  33550. if (colors) {
  33551. var color = colors[l];
  33552. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33553. }
  33554. if (index > 0) {
  33555. indices.push(idx - 1);
  33556. indices.push(idx);
  33557. }
  33558. idx++;
  33559. }
  33560. }
  33561. var vertexData = new VertexData();
  33562. vertexData.indices = indices;
  33563. vertexData.positions = positions;
  33564. if (colors) {
  33565. vertexData.colors = vertexColors;
  33566. }
  33567. return vertexData;
  33568. };
  33569. /**
  33570. * Create the VertexData of the DashedLines.
  33571. */
  33572. VertexData.CreateDashedLines = function (options) {
  33573. var dashSize = options.dashSize || 3;
  33574. var gapSize = options.gapSize || 1;
  33575. var dashNb = options.dashNb || 200;
  33576. var points = options.points;
  33577. var positions = new Array();
  33578. var indices = new Array();
  33579. var curvect = BABYLON.Vector3.Zero();
  33580. var lg = 0;
  33581. var nb = 0;
  33582. var shft = 0;
  33583. var dashshft = 0;
  33584. var curshft = 0;
  33585. var idx = 0;
  33586. var i = 0;
  33587. for (i = 0; i < points.length - 1; i++) {
  33588. points[i + 1].subtractToRef(points[i], curvect);
  33589. lg += curvect.length();
  33590. }
  33591. shft = lg / dashNb;
  33592. dashshft = dashSize * shft / (dashSize + gapSize);
  33593. for (i = 0; i < points.length - 1; i++) {
  33594. points[i + 1].subtractToRef(points[i], curvect);
  33595. nb = Math.floor(curvect.length() / shft);
  33596. curvect.normalize();
  33597. for (var j = 0; j < nb; j++) {
  33598. curshft = shft * j;
  33599. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33600. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33601. indices.push(idx, idx + 1);
  33602. idx += 2;
  33603. }
  33604. }
  33605. // Result
  33606. var vertexData = new VertexData();
  33607. vertexData.positions = positions;
  33608. vertexData.indices = indices;
  33609. return vertexData;
  33610. };
  33611. /**
  33612. * Creates the VertexData of the Ground.
  33613. */
  33614. VertexData.CreateGround = function (options) {
  33615. var indices = [];
  33616. var positions = [];
  33617. var normals = [];
  33618. var uvs = [];
  33619. var row, col;
  33620. var width = options.width || 1;
  33621. var height = options.height || 1;
  33622. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33623. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33624. for (row = 0; row <= subdivisionsY; row++) {
  33625. for (col = 0; col <= subdivisionsX; col++) {
  33626. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33627. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33628. positions.push(position.x, position.y, position.z);
  33629. normals.push(normal.x, normal.y, normal.z);
  33630. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33631. }
  33632. }
  33633. for (row = 0; row < subdivisionsY; row++) {
  33634. for (col = 0; col < subdivisionsX; col++) {
  33635. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33636. indices.push(col + 1 + row * (subdivisionsX + 1));
  33637. indices.push(col + row * (subdivisionsX + 1));
  33638. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33639. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33640. indices.push(col + row * (subdivisionsX + 1));
  33641. }
  33642. }
  33643. // Result
  33644. var vertexData = new VertexData();
  33645. vertexData.indices = indices;
  33646. vertexData.positions = positions;
  33647. vertexData.normals = normals;
  33648. vertexData.uvs = uvs;
  33649. return vertexData;
  33650. };
  33651. /**
  33652. * Creates the VertexData of the TiledGround.
  33653. */
  33654. VertexData.CreateTiledGround = function (options) {
  33655. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33656. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33657. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33658. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33659. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33660. var precision = options.precision || { w: 1, h: 1 };
  33661. var indices = new Array();
  33662. var positions = new Array();
  33663. var normals = new Array();
  33664. var uvs = new Array();
  33665. var row, col, tileRow, tileCol;
  33666. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33667. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33668. precision.w = (precision.w < 1) ? 1 : precision.w;
  33669. precision.h = (precision.h < 1) ? 1 : precision.h;
  33670. var tileSize = {
  33671. 'w': (xmax - xmin) / subdivisions.w,
  33672. 'h': (zmax - zmin) / subdivisions.h
  33673. };
  33674. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33675. // Indices
  33676. var base = positions.length / 3;
  33677. var rowLength = precision.w + 1;
  33678. for (row = 0; row < precision.h; row++) {
  33679. for (col = 0; col < precision.w; col++) {
  33680. var square = [
  33681. base + col + row * rowLength,
  33682. base + (col + 1) + row * rowLength,
  33683. base + (col + 1) + (row + 1) * rowLength,
  33684. base + col + (row + 1) * rowLength
  33685. ];
  33686. indices.push(square[1]);
  33687. indices.push(square[2]);
  33688. indices.push(square[3]);
  33689. indices.push(square[0]);
  33690. indices.push(square[1]);
  33691. indices.push(square[3]);
  33692. }
  33693. }
  33694. // Position, normals and uvs
  33695. var position = BABYLON.Vector3.Zero();
  33696. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33697. for (row = 0; row <= precision.h; row++) {
  33698. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33699. for (col = 0; col <= precision.w; col++) {
  33700. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33701. position.y = 0;
  33702. positions.push(position.x, position.y, position.z);
  33703. normals.push(normal.x, normal.y, normal.z);
  33704. uvs.push(col / precision.w, row / precision.h);
  33705. }
  33706. }
  33707. }
  33708. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33709. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33710. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33711. }
  33712. }
  33713. // Result
  33714. var vertexData = new VertexData();
  33715. vertexData.indices = indices;
  33716. vertexData.positions = positions;
  33717. vertexData.normals = normals;
  33718. vertexData.uvs = uvs;
  33719. return vertexData;
  33720. };
  33721. /**
  33722. * Creates the VertexData of the Ground designed from a heightmap.
  33723. */
  33724. VertexData.CreateGroundFromHeightMap = function (options) {
  33725. var indices = [];
  33726. var positions = [];
  33727. var normals = [];
  33728. var uvs = [];
  33729. var row, col;
  33730. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33731. // Vertices
  33732. for (row = 0; row <= options.subdivisions; row++) {
  33733. for (col = 0; col <= options.subdivisions; col++) {
  33734. 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));
  33735. // Compute height
  33736. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33737. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33738. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33739. var r = options.buffer[pos] / 255.0;
  33740. var g = options.buffer[pos + 1] / 255.0;
  33741. var b = options.buffer[pos + 2] / 255.0;
  33742. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33743. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33744. // Add vertex
  33745. positions.push(position.x, position.y, position.z);
  33746. normals.push(0, 0, 0);
  33747. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33748. }
  33749. }
  33750. // Indices
  33751. for (row = 0; row < options.subdivisions; row++) {
  33752. for (col = 0; col < options.subdivisions; col++) {
  33753. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33754. indices.push(col + 1 + row * (options.subdivisions + 1));
  33755. indices.push(col + row * (options.subdivisions + 1));
  33756. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33757. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33758. indices.push(col + row * (options.subdivisions + 1));
  33759. }
  33760. }
  33761. // Normals
  33762. VertexData.ComputeNormals(positions, indices, normals);
  33763. // Result
  33764. var vertexData = new VertexData();
  33765. vertexData.indices = indices;
  33766. vertexData.positions = positions;
  33767. vertexData.normals = normals;
  33768. vertexData.uvs = uvs;
  33769. return vertexData;
  33770. };
  33771. /**
  33772. * Creates the VertexData of the Plane.
  33773. */
  33774. VertexData.CreatePlane = function (options) {
  33775. var indices = [];
  33776. var positions = [];
  33777. var normals = [];
  33778. var uvs = [];
  33779. var width = options.width || options.size || 1;
  33780. var height = options.height || options.size || 1;
  33781. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33782. // Vertices
  33783. var halfWidth = width / 2.0;
  33784. var halfHeight = height / 2.0;
  33785. positions.push(-halfWidth, -halfHeight, 0);
  33786. normals.push(0, 0, -1.0);
  33787. uvs.push(0.0, 0.0);
  33788. positions.push(halfWidth, -halfHeight, 0);
  33789. normals.push(0, 0, -1.0);
  33790. uvs.push(1.0, 0.0);
  33791. positions.push(halfWidth, halfHeight, 0);
  33792. normals.push(0, 0, -1.0);
  33793. uvs.push(1.0, 1.0);
  33794. positions.push(-halfWidth, halfHeight, 0);
  33795. normals.push(0, 0, -1.0);
  33796. uvs.push(0.0, 1.0);
  33797. // Indices
  33798. indices.push(0);
  33799. indices.push(1);
  33800. indices.push(2);
  33801. indices.push(0);
  33802. indices.push(2);
  33803. indices.push(3);
  33804. // Sides
  33805. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33806. // Result
  33807. var vertexData = new VertexData();
  33808. vertexData.indices = indices;
  33809. vertexData.positions = positions;
  33810. vertexData.normals = normals;
  33811. vertexData.uvs = uvs;
  33812. return vertexData;
  33813. };
  33814. /**
  33815. * Creates the VertexData of the Disc or regular Polygon.
  33816. */
  33817. VertexData.CreateDisc = function (options) {
  33818. var positions = new Array();
  33819. var indices = new Array();
  33820. var normals = new Array();
  33821. var uvs = new Array();
  33822. var radius = options.radius || 0.5;
  33823. var tessellation = options.tessellation || 64;
  33824. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33825. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33826. // positions and uvs
  33827. positions.push(0, 0, 0); // disc center first
  33828. uvs.push(0.5, 0.5);
  33829. var theta = Math.PI * 2 * arc;
  33830. var step = theta / tessellation;
  33831. for (var a = 0; a < theta; a += step) {
  33832. var x = Math.cos(a);
  33833. var y = Math.sin(a);
  33834. var u = (x + 1) / 2;
  33835. var v = (1 - y) / 2;
  33836. positions.push(radius * x, radius * y, 0);
  33837. uvs.push(u, v);
  33838. }
  33839. if (arc === 1) {
  33840. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33841. uvs.push(uvs[2], uvs[3]);
  33842. }
  33843. //indices
  33844. var vertexNb = positions.length / 3;
  33845. for (var i = 1; i < vertexNb - 1; i++) {
  33846. indices.push(i + 1, 0, i);
  33847. }
  33848. // result
  33849. VertexData.ComputeNormals(positions, indices, normals);
  33850. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33851. var vertexData = new VertexData();
  33852. vertexData.indices = indices;
  33853. vertexData.positions = positions;
  33854. vertexData.normals = normals;
  33855. vertexData.uvs = uvs;
  33856. return vertexData;
  33857. };
  33858. /**
  33859. * Re-creates the VertexData of the Polygon for sideOrientation.
  33860. */
  33861. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33862. var faceUV = fUV || new Array(3);
  33863. var faceColors = fColors;
  33864. var colors = [];
  33865. // default face colors and UV if undefined
  33866. for (var f = 0; f < 3; f++) {
  33867. if (faceUV[f] === undefined) {
  33868. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33869. }
  33870. if (faceColors && faceColors[f] === undefined) {
  33871. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33872. }
  33873. }
  33874. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33875. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33876. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33877. var indices = polygon.getIndices();
  33878. // set face colours and textures
  33879. var idx = 0;
  33880. var face = 0;
  33881. for (var index = 0; index < normals.length; index += 3) {
  33882. //Edge Face no. 1
  33883. if (Math.abs(normals[index + 1]) < 0.001) {
  33884. face = 1;
  33885. }
  33886. //Top Face no. 0
  33887. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33888. face = 0;
  33889. }
  33890. //Bottom Face no. 2
  33891. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33892. face = 2;
  33893. }
  33894. idx = index / 3;
  33895. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33896. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33897. if (faceColors) {
  33898. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33899. }
  33900. }
  33901. // sides
  33902. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33903. // Result
  33904. var vertexData = new VertexData();
  33905. vertexData.indices = indices;
  33906. vertexData.positions = positions;
  33907. vertexData.normals = normals;
  33908. vertexData.uvs = uvs;
  33909. if (faceColors) {
  33910. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33911. vertexData.colors = totalColors;
  33912. }
  33913. return vertexData;
  33914. };
  33915. /**
  33916. * Creates the VertexData of the IcoSphere.
  33917. */
  33918. VertexData.CreateIcoSphere = function (options) {
  33919. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33920. var radius = options.radius || 1;
  33921. var flat = (options.flat === undefined) ? true : options.flat;
  33922. var subdivisions = options.subdivisions || 4;
  33923. var radiusX = options.radiusX || radius;
  33924. var radiusY = options.radiusY || radius;
  33925. var radiusZ = options.radiusZ || radius;
  33926. var t = (1 + Math.sqrt(5)) / 2;
  33927. // 12 vertex x,y,z
  33928. var ico_vertices = [
  33929. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33930. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33931. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33932. ];
  33933. // index of 3 vertex makes a face of icopshere
  33934. var ico_indices = [
  33935. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33936. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33937. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33938. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33939. ];
  33940. // vertex for uv have aliased position, not for UV
  33941. var vertices_unalias_id = [
  33942. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33943. // vertex alias
  33944. 0,
  33945. 2,
  33946. 3,
  33947. 3,
  33948. 3,
  33949. 4,
  33950. 7,
  33951. 8,
  33952. 9,
  33953. 9,
  33954. 10,
  33955. 11 // 23: B + 12
  33956. ];
  33957. // uv as integer step (not pixels !)
  33958. var ico_vertexuv = [
  33959. 5, 1, 3, 1, 6, 4, 0, 0,
  33960. 5, 3, 4, 2, 2, 2, 4, 0,
  33961. 2, 0, 1, 1, 6, 0, 6, 2,
  33962. // vertex alias (for same vertex on different faces)
  33963. 0, 4,
  33964. 3, 3,
  33965. 4, 4,
  33966. 3, 1,
  33967. 4, 2,
  33968. 4, 4,
  33969. 0, 2,
  33970. 1, 1,
  33971. 2, 2,
  33972. 3, 3,
  33973. 1, 3,
  33974. 2, 4 // 23: B + 12
  33975. ];
  33976. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33977. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33978. // First island of uv mapping
  33979. // v = 4h 3+ 2
  33980. // v = 3h 9+ 4
  33981. // v = 2h 9+ 5 B
  33982. // v = 1h 9 1 0
  33983. // v = 0h 3 8 7 A
  33984. // u = 0 1 2 3 4 5 6 *a
  33985. // Second island of uv mapping
  33986. // v = 4h 0+ B+ 4+
  33987. // v = 3h A+ 2+
  33988. // v = 2h 7+ 6 3+
  33989. // v = 1h 8+ 3+
  33990. // v = 0h
  33991. // u = 0 1 2 3 4 5 6 *a
  33992. // Face layout on texture UV mapping
  33993. // ============
  33994. // \ 4 /\ 16 / ======
  33995. // \ / \ / /\ 11 /
  33996. // \/ 7 \/ / \ /
  33997. // ======= / 10 \/
  33998. // /\ 17 /\ =======
  33999. // / \ / \ \ 15 /\
  34000. // / 8 \/ 12 \ \ / \
  34001. // ============ \/ 6 \
  34002. // \ 18 /\ ============
  34003. // \ / \ \ 5 /\ 0 /
  34004. // \/ 13 \ \ / \ /
  34005. // ======= \/ 1 \/
  34006. // =============
  34007. // /\ 19 /\ 2 /\
  34008. // / \ / \ / \
  34009. // / 14 \/ 9 \/ 3 \
  34010. // ===================
  34011. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34012. var ustep = 138 / 1024;
  34013. var vstep = 239 / 1024;
  34014. var uoffset = 60 / 1024;
  34015. var voffset = 26 / 1024;
  34016. // Second island should have margin, not to touch the first island
  34017. // avoid any borderline artefact in pixel rounding
  34018. var island_u_offset = -40 / 1024;
  34019. var island_v_offset = +20 / 1024;
  34020. // face is either island 0 or 1 :
  34021. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34022. var island = [
  34023. 0, 0, 0, 0, 1,
  34024. 0, 0, 1, 1, 0,
  34025. 0, 0, 1, 1, 0,
  34026. 0, 1, 1, 1, 0 // 15 - 19
  34027. ];
  34028. var indices = new Array();
  34029. var positions = new Array();
  34030. var normals = new Array();
  34031. var uvs = new Array();
  34032. var current_indice = 0;
  34033. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34034. var face_vertex_pos = new Array(3);
  34035. var face_vertex_uv = new Array(3);
  34036. var v012;
  34037. for (v012 = 0; v012 < 3; v012++) {
  34038. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34039. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34040. }
  34041. // create all with normals
  34042. for (var face = 0; face < 20; face++) {
  34043. // 3 vertex per face
  34044. for (v012 = 0; v012 < 3; v012++) {
  34045. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34046. var v_id = ico_indices[3 * face + v012];
  34047. // vertex have 3D position (x,y,z)
  34048. 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]);
  34049. // Normalize to get normal, then scale to radius
  34050. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34051. // uv Coordinates from vertex ID
  34052. 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);
  34053. }
  34054. // Subdivide the face (interpolate pos, norm, uv)
  34055. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34056. // - norm is linear interpolation of vertex corner normal
  34057. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34058. // - uv is linear interpolation
  34059. //
  34060. // Topology is as below for sub-divide by 2
  34061. // vertex shown as v0,v1,v2
  34062. // interp index is i1 to progress in range [v0,v1[
  34063. // interp index is i2 to progress in range [v0,v2[
  34064. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34065. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34066. //
  34067. //
  34068. // i2 v2
  34069. // ^ ^
  34070. // / / \
  34071. // / / \
  34072. // / / \
  34073. // / / (0,1) \
  34074. // / #---------\
  34075. // / / \ (0,0)'/ \
  34076. // / / \ / \
  34077. // / / \ / \
  34078. // / / (0,0) \ / (1,0) \
  34079. // / #---------#---------\
  34080. // v0 v1
  34081. //
  34082. // --------------------> i1
  34083. //
  34084. // interp of (i1,i2):
  34085. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34086. // along i1 : lerp(x0,x1, i1/(S-i2))
  34087. //
  34088. // centroid of triangle is needed to get help normal computation
  34089. // (c1,c2) are used for centroid location
  34090. var interp_vertex = function (i1, i2, c1, c2) {
  34091. // vertex is interpolated from
  34092. // - face_vertex_pos[0..2]
  34093. // - face_vertex_uv[0..2]
  34094. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34095. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34096. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34097. pos_interp.normalize();
  34098. var vertex_normal;
  34099. if (flat) {
  34100. // in flat mode, recalculate normal as face centroid normal
  34101. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34102. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34103. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34104. }
  34105. else {
  34106. // in smooth mode, recalculate normal from each single vertex position
  34107. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34108. }
  34109. // Vertex normal need correction due to X,Y,Z radius scaling
  34110. vertex_normal.x /= radiusX;
  34111. vertex_normal.y /= radiusY;
  34112. vertex_normal.z /= radiusZ;
  34113. vertex_normal.normalize();
  34114. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34115. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34116. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34117. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34118. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34119. uvs.push(uv_interp.x, uv_interp.y);
  34120. // push each vertex has member of a face
  34121. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34122. indices.push(current_indice);
  34123. current_indice++;
  34124. };
  34125. for (var i2 = 0; i2 < subdivisions; i2++) {
  34126. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34127. // face : (i1,i2) for /\ :
  34128. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34129. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34130. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34131. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34132. if (i1 + i2 + 1 < subdivisions) {
  34133. // face : (i1,i2)' for \/ :
  34134. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34135. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34136. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34137. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34138. }
  34139. }
  34140. }
  34141. }
  34142. // Sides
  34143. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34144. // Result
  34145. var vertexData = new VertexData();
  34146. vertexData.indices = indices;
  34147. vertexData.positions = positions;
  34148. vertexData.normals = normals;
  34149. vertexData.uvs = uvs;
  34150. return vertexData;
  34151. };
  34152. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34153. /**
  34154. * Creates the VertexData of the Polyhedron.
  34155. */
  34156. VertexData.CreatePolyhedron = function (options) {
  34157. // provided polyhedron types :
  34158. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34159. // 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)
  34160. var polyhedra = [];
  34161. 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]] };
  34162. 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]] };
  34163. polyhedra[2] = {
  34164. 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]],
  34165. 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]]
  34166. };
  34167. polyhedra[3] = {
  34168. 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]],
  34169. 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]]
  34170. };
  34171. polyhedra[4] = {
  34172. 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]],
  34173. 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]]
  34174. };
  34175. 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]] };
  34176. 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]] };
  34177. 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]] };
  34178. 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]] };
  34179. 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]] };
  34180. 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]] };
  34181. 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]] };
  34182. 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]] };
  34183. 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]] };
  34184. polyhedra[14] = {
  34185. 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]],
  34186. 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]]
  34187. };
  34188. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34189. var size = options.size;
  34190. var sizeX = options.sizeX || size || 1;
  34191. var sizeY = options.sizeY || size || 1;
  34192. var sizeZ = options.sizeZ || size || 1;
  34193. var data = options.custom || polyhedra[type];
  34194. var nbfaces = data.face.length;
  34195. var faceUV = options.faceUV || new Array(nbfaces);
  34196. var faceColors = options.faceColors;
  34197. var flat = (options.flat === undefined) ? true : options.flat;
  34198. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34199. var positions = new Array();
  34200. var indices = new Array();
  34201. var normals = new Array();
  34202. var uvs = new Array();
  34203. var colors = new Array();
  34204. var index = 0;
  34205. var faceIdx = 0; // face cursor in the array "indexes"
  34206. var indexes = new Array();
  34207. var i = 0;
  34208. var f = 0;
  34209. var u, v, ang, x, y, tmp;
  34210. // default face colors and UV if undefined
  34211. if (flat) {
  34212. for (f = 0; f < nbfaces; f++) {
  34213. if (faceColors && faceColors[f] === undefined) {
  34214. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34215. }
  34216. if (faceUV && faceUV[f] === undefined) {
  34217. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34218. }
  34219. }
  34220. }
  34221. if (!flat) {
  34222. for (i = 0; i < data.vertex.length; i++) {
  34223. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34224. uvs.push(0, 0);
  34225. }
  34226. for (f = 0; f < nbfaces; f++) {
  34227. for (i = 0; i < data.face[f].length - 2; i++) {
  34228. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34229. }
  34230. }
  34231. }
  34232. else {
  34233. for (f = 0; f < nbfaces; f++) {
  34234. var fl = data.face[f].length; // number of vertices of the current face
  34235. ang = 2 * Math.PI / fl;
  34236. x = 0.5 * Math.tan(ang / 2);
  34237. y = 0.5;
  34238. // positions, uvs, colors
  34239. for (i = 0; i < fl; i++) {
  34240. // positions
  34241. 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);
  34242. indexes.push(index);
  34243. index++;
  34244. // uvs
  34245. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34246. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34247. uvs.push(u, v);
  34248. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34249. y = x * Math.sin(ang) + y * Math.cos(ang);
  34250. x = tmp;
  34251. // colors
  34252. if (faceColors) {
  34253. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34254. }
  34255. }
  34256. // indices from indexes
  34257. for (i = 0; i < fl - 2; i++) {
  34258. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34259. }
  34260. faceIdx += fl;
  34261. }
  34262. }
  34263. VertexData.ComputeNormals(positions, indices, normals);
  34264. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34265. var vertexData = new VertexData();
  34266. vertexData.positions = positions;
  34267. vertexData.indices = indices;
  34268. vertexData.normals = normals;
  34269. vertexData.uvs = uvs;
  34270. if (faceColors && flat) {
  34271. vertexData.colors = colors;
  34272. }
  34273. return vertexData;
  34274. };
  34275. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34276. /**
  34277. * Creates the VertexData of the Torus Knot.
  34278. */
  34279. VertexData.CreateTorusKnot = function (options) {
  34280. var indices = new Array();
  34281. var positions = new Array();
  34282. var normals = new Array();
  34283. var uvs = new Array();
  34284. var radius = options.radius || 2;
  34285. var tube = options.tube || 0.5;
  34286. var radialSegments = options.radialSegments || 32;
  34287. var tubularSegments = options.tubularSegments || 32;
  34288. var p = options.p || 2;
  34289. var q = options.q || 3;
  34290. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34291. // Helper
  34292. var getPos = function (angle) {
  34293. var cu = Math.cos(angle);
  34294. var su = Math.sin(angle);
  34295. var quOverP = q / p * angle;
  34296. var cs = Math.cos(quOverP);
  34297. var tx = radius * (2 + cs) * 0.5 * cu;
  34298. var ty = radius * (2 + cs) * su * 0.5;
  34299. var tz = radius * Math.sin(quOverP) * 0.5;
  34300. return new BABYLON.Vector3(tx, ty, tz);
  34301. };
  34302. // Vertices
  34303. var i;
  34304. var j;
  34305. for (i = 0; i <= radialSegments; i++) {
  34306. var modI = i % radialSegments;
  34307. var u = modI / radialSegments * 2 * p * Math.PI;
  34308. var p1 = getPos(u);
  34309. var p2 = getPos(u + 0.01);
  34310. var tang = p2.subtract(p1);
  34311. var n = p2.add(p1);
  34312. var bitan = BABYLON.Vector3.Cross(tang, n);
  34313. n = BABYLON.Vector3.Cross(bitan, tang);
  34314. bitan.normalize();
  34315. n.normalize();
  34316. for (j = 0; j < tubularSegments; j++) {
  34317. var modJ = j % tubularSegments;
  34318. var v = modJ / tubularSegments * 2 * Math.PI;
  34319. var cx = -tube * Math.cos(v);
  34320. var cy = tube * Math.sin(v);
  34321. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34322. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34323. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34324. uvs.push(i / radialSegments);
  34325. uvs.push(j / tubularSegments);
  34326. }
  34327. }
  34328. for (i = 0; i < radialSegments; i++) {
  34329. for (j = 0; j < tubularSegments; j++) {
  34330. var jNext = (j + 1) % tubularSegments;
  34331. var a = i * tubularSegments + j;
  34332. var b = (i + 1) * tubularSegments + j;
  34333. var c = (i + 1) * tubularSegments + jNext;
  34334. var d = i * tubularSegments + jNext;
  34335. indices.push(d);
  34336. indices.push(b);
  34337. indices.push(a);
  34338. indices.push(d);
  34339. indices.push(c);
  34340. indices.push(b);
  34341. }
  34342. }
  34343. // Normals
  34344. VertexData.ComputeNormals(positions, indices, normals);
  34345. // Sides
  34346. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34347. // Result
  34348. var vertexData = new VertexData();
  34349. vertexData.indices = indices;
  34350. vertexData.positions = positions;
  34351. vertexData.normals = normals;
  34352. vertexData.uvs = uvs;
  34353. return vertexData;
  34354. };
  34355. // Tools
  34356. /**
  34357. * @param {any} - positions (number[] or Float32Array)
  34358. * @param {any} - indices (number[] or Uint16Array)
  34359. * @param {any} - normals (number[] or Float32Array)
  34360. * options (optional) :
  34361. * facetPositions : optional array of facet positions (vector3)
  34362. * facetNormals : optional array of facet normals (vector3)
  34363. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34364. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34365. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34366. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34367. * bInfo : optional bounding info, required for facetPartitioning computation
  34368. * useRightHandedSystem: optional boolean to for right handed system computation
  34369. * depthSort : optional boolean to enable the facet depth sort computation
  34370. * distanceTo : optional Vector3 to compute the facet depth from this location
  34371. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34372. */
  34373. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34374. // temporary scalar variables
  34375. var index = 0; // facet index
  34376. var p1p2x = 0.0; // p1p2 vector x coordinate
  34377. var p1p2y = 0.0; // p1p2 vector y coordinate
  34378. var p1p2z = 0.0; // p1p2 vector z coordinate
  34379. var p3p2x = 0.0; // p3p2 vector x coordinate
  34380. var p3p2y = 0.0; // p3p2 vector y coordinate
  34381. var p3p2z = 0.0; // p3p2 vector z coordinate
  34382. var faceNormalx = 0.0; // facet normal x coordinate
  34383. var faceNormaly = 0.0; // facet normal y coordinate
  34384. var faceNormalz = 0.0; // facet normal z coordinate
  34385. var length = 0.0; // facet normal length before normalization
  34386. var v1x = 0; // vector1 x index in the positions array
  34387. var v1y = 0; // vector1 y index in the positions array
  34388. var v1z = 0; // vector1 z index in the positions array
  34389. var v2x = 0; // vector2 x index in the positions array
  34390. var v2y = 0; // vector2 y index in the positions array
  34391. var v2z = 0; // vector2 z index in the positions array
  34392. var v3x = 0; // vector3 x index in the positions array
  34393. var v3y = 0; // vector3 y index in the positions array
  34394. var v3z = 0; // vector3 z index in the positions array
  34395. var computeFacetNormals = false;
  34396. var computeFacetPositions = false;
  34397. var computeFacetPartitioning = false;
  34398. var computeDepthSort = false;
  34399. var faceNormalSign = 1;
  34400. var ratio = 0;
  34401. var distanceTo = null;
  34402. if (options) {
  34403. computeFacetNormals = (options.facetNormals) ? true : false;
  34404. computeFacetPositions = (options.facetPositions) ? true : false;
  34405. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34406. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34407. ratio = options.ratio || 0;
  34408. computeDepthSort = (options.depthSort) ? true : false;
  34409. distanceTo = (options.distanceTo);
  34410. if (computeDepthSort) {
  34411. if (distanceTo === undefined) {
  34412. distanceTo = BABYLON.Vector3.Zero();
  34413. }
  34414. var depthSortedFacets = options.depthSortedFacets;
  34415. }
  34416. }
  34417. // facetPartitioning reinit if needed
  34418. var xSubRatio = 0;
  34419. var ySubRatio = 0;
  34420. var zSubRatio = 0;
  34421. var subSq = 0;
  34422. if (computeFacetPartitioning && options && options.bbSize) {
  34423. var ox = 0; // X partitioning index for facet position
  34424. var oy = 0; // Y partinioning index for facet position
  34425. var oz = 0; // Z partinioning index for facet position
  34426. var b1x = 0; // X partitioning index for facet v1 vertex
  34427. var b1y = 0; // Y partitioning index for facet v1 vertex
  34428. var b1z = 0; // z partitioning index for facet v1 vertex
  34429. var b2x = 0; // X partitioning index for facet v2 vertex
  34430. var b2y = 0; // Y partitioning index for facet v2 vertex
  34431. var b2z = 0; // Z partitioning index for facet v2 vertex
  34432. var b3x = 0; // X partitioning index for facet v3 vertex
  34433. var b3y = 0; // Y partitioning index for facet v3 vertex
  34434. var b3z = 0; // Z partitioning index for facet v3 vertex
  34435. var block_idx_o = 0; // facet barycenter block index
  34436. var block_idx_v1 = 0; // v1 vertex block index
  34437. var block_idx_v2 = 0; // v2 vertex block index
  34438. var block_idx_v3 = 0; // v3 vertex block index
  34439. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34440. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34441. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34442. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34443. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34444. subSq = options.subDiv.max * options.subDiv.max;
  34445. options.facetPartitioning.length = 0;
  34446. }
  34447. // reset the normals
  34448. for (index = 0; index < positions.length; index++) {
  34449. normals[index] = 0.0;
  34450. }
  34451. // Loop : 1 indice triplet = 1 facet
  34452. var nbFaces = (indices.length / 3) | 0;
  34453. for (index = 0; index < nbFaces; index++) {
  34454. // get the indexes of the coordinates of each vertex of the facet
  34455. v1x = indices[index * 3] * 3;
  34456. v1y = v1x + 1;
  34457. v1z = v1x + 2;
  34458. v2x = indices[index * 3 + 1] * 3;
  34459. v2y = v2x + 1;
  34460. v2z = v2x + 2;
  34461. v3x = indices[index * 3 + 2] * 3;
  34462. v3y = v3x + 1;
  34463. v3z = v3x + 2;
  34464. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34465. p1p2y = positions[v1y] - positions[v2y];
  34466. p1p2z = positions[v1z] - positions[v2z];
  34467. p3p2x = positions[v3x] - positions[v2x];
  34468. p3p2y = positions[v3y] - positions[v2y];
  34469. p3p2z = positions[v3z] - positions[v2z];
  34470. // compute the face normal with the cross product
  34471. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34472. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34473. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34474. // normalize this normal and store it in the array facetData
  34475. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34476. length = (length === 0) ? 1.0 : length;
  34477. faceNormalx /= length;
  34478. faceNormaly /= length;
  34479. faceNormalz /= length;
  34480. if (computeFacetNormals && options) {
  34481. options.facetNormals[index].x = faceNormalx;
  34482. options.facetNormals[index].y = faceNormaly;
  34483. options.facetNormals[index].z = faceNormalz;
  34484. }
  34485. if (computeFacetPositions && options) {
  34486. // compute and the facet barycenter coordinates in the array facetPositions
  34487. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34488. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34489. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34490. }
  34491. if (computeFacetPartitioning && options) {
  34492. // store the facet indexes in arrays in the main facetPartitioning array :
  34493. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34494. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34495. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34496. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34497. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34498. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34499. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34500. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34501. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34502. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34503. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34504. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34505. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34506. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34507. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34508. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34509. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34510. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34511. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34512. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34513. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34514. // push each facet index in each block containing the vertex
  34515. options.facetPartitioning[block_idx_v1].push(index);
  34516. if (block_idx_v2 != block_idx_v1) {
  34517. options.facetPartitioning[block_idx_v2].push(index);
  34518. }
  34519. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34520. options.facetPartitioning[block_idx_v3].push(index);
  34521. }
  34522. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34523. options.facetPartitioning[block_idx_o].push(index);
  34524. }
  34525. }
  34526. if (computeDepthSort && options && options.facetPositions) {
  34527. var dsf = depthSortedFacets[index];
  34528. dsf.ind = index * 3;
  34529. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34530. }
  34531. // compute the normals anyway
  34532. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34533. normals[v1y] += faceNormaly;
  34534. normals[v1z] += faceNormalz;
  34535. normals[v2x] += faceNormalx;
  34536. normals[v2y] += faceNormaly;
  34537. normals[v2z] += faceNormalz;
  34538. normals[v3x] += faceNormalx;
  34539. normals[v3y] += faceNormaly;
  34540. normals[v3z] += faceNormalz;
  34541. }
  34542. // last normalization of each normal
  34543. for (index = 0; index < normals.length / 3; index++) {
  34544. faceNormalx = normals[index * 3];
  34545. faceNormaly = normals[index * 3 + 1];
  34546. faceNormalz = normals[index * 3 + 2];
  34547. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34548. length = (length === 0) ? 1.0 : length;
  34549. faceNormalx /= length;
  34550. faceNormaly /= length;
  34551. faceNormalz /= length;
  34552. normals[index * 3] = faceNormalx;
  34553. normals[index * 3 + 1] = faceNormaly;
  34554. normals[index * 3 + 2] = faceNormalz;
  34555. }
  34556. };
  34557. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34558. var li = indices.length;
  34559. var ln = normals.length;
  34560. var i;
  34561. var n;
  34562. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34563. switch (sideOrientation) {
  34564. case BABYLON.Mesh.FRONTSIDE:
  34565. // nothing changed
  34566. break;
  34567. case BABYLON.Mesh.BACKSIDE:
  34568. var tmp;
  34569. // indices
  34570. for (i = 0; i < li; i += 3) {
  34571. tmp = indices[i];
  34572. indices[i] = indices[i + 2];
  34573. indices[i + 2] = tmp;
  34574. }
  34575. // normals
  34576. for (n = 0; n < ln; n++) {
  34577. normals[n] = -normals[n];
  34578. }
  34579. break;
  34580. case BABYLON.Mesh.DOUBLESIDE:
  34581. // positions
  34582. var lp = positions.length;
  34583. var l = lp / 3;
  34584. for (var p = 0; p < lp; p++) {
  34585. positions[lp + p] = positions[p];
  34586. }
  34587. // indices
  34588. for (i = 0; i < li; i += 3) {
  34589. indices[i + li] = indices[i + 2] + l;
  34590. indices[i + 1 + li] = indices[i + 1] + l;
  34591. indices[i + 2 + li] = indices[i] + l;
  34592. }
  34593. // normals
  34594. for (n = 0; n < ln; n++) {
  34595. normals[ln + n] = -normals[n];
  34596. }
  34597. // uvs
  34598. var lu = uvs.length;
  34599. var u = 0;
  34600. for (u = 0; u < lu; u++) {
  34601. uvs[u + lu] = uvs[u];
  34602. }
  34603. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34604. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34605. u = 0;
  34606. for (i = 0; i < lu / 2; i++) {
  34607. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34608. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34609. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34610. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34611. u += 2;
  34612. }
  34613. break;
  34614. }
  34615. };
  34616. /**
  34617. * Creates a new VertexData from the imported parameters.
  34618. */
  34619. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34620. var vertexData = new VertexData();
  34621. // positions
  34622. var positions = parsedVertexData.positions;
  34623. if (positions) {
  34624. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34625. }
  34626. // normals
  34627. var normals = parsedVertexData.normals;
  34628. if (normals) {
  34629. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34630. }
  34631. // tangents
  34632. var tangents = parsedVertexData.tangents;
  34633. if (tangents) {
  34634. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34635. }
  34636. // uvs
  34637. var uvs = parsedVertexData.uvs;
  34638. if (uvs) {
  34639. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34640. }
  34641. // uv2s
  34642. var uv2s = parsedVertexData.uv2s;
  34643. if (uv2s) {
  34644. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34645. }
  34646. // uv3s
  34647. var uv3s = parsedVertexData.uv3s;
  34648. if (uv3s) {
  34649. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34650. }
  34651. // uv4s
  34652. var uv4s = parsedVertexData.uv4s;
  34653. if (uv4s) {
  34654. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34655. }
  34656. // uv5s
  34657. var uv5s = parsedVertexData.uv5s;
  34658. if (uv5s) {
  34659. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34660. }
  34661. // uv6s
  34662. var uv6s = parsedVertexData.uv6s;
  34663. if (uv6s) {
  34664. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34665. }
  34666. // colors
  34667. var colors = parsedVertexData.colors;
  34668. if (colors) {
  34669. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34670. }
  34671. // matricesIndices
  34672. var matricesIndices = parsedVertexData.matricesIndices;
  34673. if (matricesIndices) {
  34674. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34675. }
  34676. // matricesWeights
  34677. var matricesWeights = parsedVertexData.matricesWeights;
  34678. if (matricesWeights) {
  34679. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34680. }
  34681. // indices
  34682. var indices = parsedVertexData.indices;
  34683. if (indices) {
  34684. vertexData.indices = indices;
  34685. }
  34686. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34687. };
  34688. return VertexData;
  34689. }());
  34690. BABYLON.VertexData = VertexData;
  34691. })(BABYLON || (BABYLON = {}));
  34692. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34693. var BABYLON;
  34694. (function (BABYLON) {
  34695. /**
  34696. * Class used to store geometry data (vertex buffers + index buffer)
  34697. */
  34698. var Geometry = /** @class */ (function () {
  34699. /**
  34700. * Creates a new geometry
  34701. * @param id defines the unique ID
  34702. * @param scene defines the hosting scene
  34703. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34704. * @param updatable defines if geometry must be updatable (false by default)
  34705. * @param mesh defines the mesh that will be associated with the geometry
  34706. */
  34707. function Geometry(id, scene, vertexData, updatable, mesh) {
  34708. if (updatable === void 0) { updatable = false; }
  34709. if (mesh === void 0) { mesh = null; }
  34710. /**
  34711. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34712. */
  34713. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34714. this._totalVertices = 0;
  34715. this._isDisposed = false;
  34716. this._indexBufferIsUpdatable = false;
  34717. this.id = id;
  34718. this._engine = scene.getEngine();
  34719. this._meshes = [];
  34720. this._scene = scene;
  34721. //Init vertex buffer cache
  34722. this._vertexBuffers = {};
  34723. this._indices = [];
  34724. this._updatable = updatable;
  34725. // vertexData
  34726. if (vertexData) {
  34727. this.setAllVerticesData(vertexData, updatable);
  34728. }
  34729. else {
  34730. this._totalVertices = 0;
  34731. this._indices = [];
  34732. }
  34733. if (this._engine.getCaps().vertexArrayObject) {
  34734. this._vertexArrayObjects = {};
  34735. }
  34736. // applyToMesh
  34737. if (mesh) {
  34738. if (mesh.getClassName() === "LinesMesh") {
  34739. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34740. this.updateExtend();
  34741. }
  34742. this.applyToMesh(mesh);
  34743. mesh.computeWorldMatrix(true);
  34744. }
  34745. }
  34746. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34747. /**
  34748. * 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
  34749. */
  34750. get: function () {
  34751. return this._boundingBias;
  34752. },
  34753. /**
  34754. * 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
  34755. */
  34756. set: function (value) {
  34757. if (this._boundingBias && this._boundingBias.equals(value)) {
  34758. return;
  34759. }
  34760. this._boundingBias = value.clone();
  34761. this.updateBoundingInfo(true, null);
  34762. },
  34763. enumerable: true,
  34764. configurable: true
  34765. });
  34766. /**
  34767. * Static function used to attach a new empty geometry to a mesh
  34768. * @param mesh defines the mesh to attach the geometry to
  34769. * @returns the new {BABYLON.Geometry}
  34770. */
  34771. Geometry.CreateGeometryForMesh = function (mesh) {
  34772. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34773. geometry.applyToMesh(mesh);
  34774. return geometry;
  34775. };
  34776. Object.defineProperty(Geometry.prototype, "extend", {
  34777. /**
  34778. * Gets the current extend of the geometry
  34779. */
  34780. get: function () {
  34781. return this._extend;
  34782. },
  34783. enumerable: true,
  34784. configurable: true
  34785. });
  34786. /**
  34787. * Gets the hosting scene
  34788. * @returns the hosting {BABYLON.Scene}
  34789. */
  34790. Geometry.prototype.getScene = function () {
  34791. return this._scene;
  34792. };
  34793. /**
  34794. * Gets the hosting engine
  34795. * @returns the hosting {BABYLON.Engine}
  34796. */
  34797. Geometry.prototype.getEngine = function () {
  34798. return this._engine;
  34799. };
  34800. /**
  34801. * Defines if the geometry is ready to use
  34802. * @returns true if the geometry is ready to be used
  34803. */
  34804. Geometry.prototype.isReady = function () {
  34805. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34806. };
  34807. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34808. /**
  34809. * Gets a value indicating that the geometry should not be serialized
  34810. */
  34811. get: function () {
  34812. for (var index = 0; index < this._meshes.length; index++) {
  34813. if (!this._meshes[index].doNotSerialize) {
  34814. return false;
  34815. }
  34816. }
  34817. return true;
  34818. },
  34819. enumerable: true,
  34820. configurable: true
  34821. });
  34822. /** @ignore */
  34823. Geometry.prototype._rebuild = function () {
  34824. if (this._vertexArrayObjects) {
  34825. this._vertexArrayObjects = {};
  34826. }
  34827. // Index buffer
  34828. if (this._meshes.length !== 0 && this._indices) {
  34829. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34830. }
  34831. // Vertex buffers
  34832. for (var key in this._vertexBuffers) {
  34833. var vertexBuffer = this._vertexBuffers[key];
  34834. vertexBuffer._rebuild();
  34835. }
  34836. };
  34837. /**
  34838. * Affects all gemetry data in one call
  34839. * @param vertexData defines the geometry data
  34840. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34841. */
  34842. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34843. vertexData.applyToGeometry(this, updatable);
  34844. this.notifyUpdate();
  34845. };
  34846. /**
  34847. * Set specific vertex data
  34848. * @param kind defines the data kind (Position, normal, etc...)
  34849. * @param data defines the vertex data to use
  34850. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34851. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34852. */
  34853. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34854. if (updatable === void 0) { updatable = false; }
  34855. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34856. this.setVerticesBuffer(buffer);
  34857. };
  34858. /**
  34859. * Removes a specific vertex data
  34860. * @param kind defines the data kind (Position, normal, etc...)
  34861. */
  34862. Geometry.prototype.removeVerticesData = function (kind) {
  34863. if (this._vertexBuffers[kind]) {
  34864. this._vertexBuffers[kind].dispose();
  34865. delete this._vertexBuffers[kind];
  34866. }
  34867. };
  34868. /**
  34869. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34870. * @param buffer defines the vertex buffer to use
  34871. */
  34872. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34873. var kind = buffer.getKind();
  34874. if (this._vertexBuffers[kind]) {
  34875. this._vertexBuffers[kind].dispose();
  34876. }
  34877. this._vertexBuffers[kind] = buffer;
  34878. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34879. var data = buffer.getData();
  34880. var stride = buffer.getStrideSize();
  34881. this._totalVertices = data.length / stride;
  34882. this.updateExtend(data, stride);
  34883. this._resetPointsArrayCache();
  34884. var meshes = this._meshes;
  34885. var numOfMeshes = meshes.length;
  34886. for (var index = 0; index < numOfMeshes; index++) {
  34887. var mesh = meshes[index];
  34888. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34889. mesh._createGlobalSubMesh(false);
  34890. mesh.computeWorldMatrix(true);
  34891. }
  34892. }
  34893. this.notifyUpdate(kind);
  34894. if (this._vertexArrayObjects) {
  34895. this._disposeVertexArrayObjects();
  34896. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34897. }
  34898. };
  34899. /**
  34900. * Update a specific vertex buffer
  34901. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34902. * It will do nothing if the buffer is not updatable
  34903. * @param kind defines the data kind (Position, normal, etc...)
  34904. * @param data defines the data to use
  34905. * @param offset defines the offset in the target buffer where to store the data
  34906. */
  34907. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34908. var vertexBuffer = this.getVertexBuffer(kind);
  34909. if (!vertexBuffer) {
  34910. return;
  34911. }
  34912. vertexBuffer.updateDirectly(data, offset);
  34913. this.notifyUpdate(kind);
  34914. };
  34915. /**
  34916. * Update a specific vertex buffer
  34917. * This function will create a new buffer if the current one is not updatable
  34918. * @param kind defines the data kind (Position, normal, etc...)
  34919. * @param data defines the data to use
  34920. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34921. */
  34922. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34923. if (updateExtends === void 0) { updateExtends = false; }
  34924. var vertexBuffer = this.getVertexBuffer(kind);
  34925. if (!vertexBuffer) {
  34926. return;
  34927. }
  34928. vertexBuffer.update(data);
  34929. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34930. var stride = vertexBuffer.getStrideSize();
  34931. this._totalVertices = data.length / stride;
  34932. this.updateBoundingInfo(updateExtends, data);
  34933. }
  34934. this.notifyUpdate(kind);
  34935. };
  34936. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34937. if (updateExtends) {
  34938. this.updateExtend(data);
  34939. }
  34940. var meshes = this._meshes;
  34941. var numOfMeshes = meshes.length;
  34942. this._resetPointsArrayCache();
  34943. for (var index = 0; index < numOfMeshes; index++) {
  34944. var mesh = meshes[index];
  34945. if (updateExtends) {
  34946. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34947. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34948. var subMesh = mesh.subMeshes[subIndex];
  34949. subMesh.refreshBoundingInfo();
  34950. }
  34951. }
  34952. }
  34953. };
  34954. /** @ignore */
  34955. Geometry.prototype._bind = function (effect, indexToBind) {
  34956. if (!effect) {
  34957. return;
  34958. }
  34959. if (indexToBind === undefined) {
  34960. indexToBind = this._indexBuffer;
  34961. }
  34962. var vbs = this.getVertexBuffers();
  34963. if (!vbs) {
  34964. return;
  34965. }
  34966. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34967. this._engine.bindBuffers(vbs, indexToBind, effect);
  34968. return;
  34969. }
  34970. // Using VAO
  34971. if (!this._vertexArrayObjects[effect.key]) {
  34972. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34973. }
  34974. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34975. };
  34976. /**
  34977. * Gets total number of vertices
  34978. * @returns the total number of vertices
  34979. */
  34980. Geometry.prototype.getTotalVertices = function () {
  34981. if (!this.isReady()) {
  34982. return 0;
  34983. }
  34984. return this._totalVertices;
  34985. };
  34986. /**
  34987. * Gets a specific vertex data attached to this geometry
  34988. * @param kind defines the data kind (Position, normal, etc...)
  34989. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34990. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34991. * @returns a float array containing vertex data
  34992. */
  34993. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34994. var vertexBuffer = this.getVertexBuffer(kind);
  34995. if (!vertexBuffer) {
  34996. return null;
  34997. }
  34998. var orig = vertexBuffer.getData();
  34999. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35000. return orig;
  35001. }
  35002. else {
  35003. var len = orig.length;
  35004. var copy = [];
  35005. for (var i = 0; i < len; i++) {
  35006. copy.push(orig[i]);
  35007. }
  35008. return copy;
  35009. }
  35010. };
  35011. /**
  35012. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35013. * @param kind defines the data kind (Position, normal, etc...)
  35014. * @returns true if the vertex buffer with the specified kind is updatable
  35015. */
  35016. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35017. var vb = this._vertexBuffers[kind];
  35018. if (!vb) {
  35019. return false;
  35020. }
  35021. return vb.isUpdatable();
  35022. };
  35023. /**
  35024. * Gets a specific vertex buffer
  35025. * @param kind defines the data kind (Position, normal, etc...)
  35026. * @returns a {BABYLON.VertexBuffer}
  35027. */
  35028. Geometry.prototype.getVertexBuffer = function (kind) {
  35029. if (!this.isReady()) {
  35030. return null;
  35031. }
  35032. return this._vertexBuffers[kind];
  35033. };
  35034. /**
  35035. * Returns all vertex buffers
  35036. * @return an object holding all vertex buffers indexed by kind
  35037. */
  35038. Geometry.prototype.getVertexBuffers = function () {
  35039. if (!this.isReady()) {
  35040. return null;
  35041. }
  35042. return this._vertexBuffers;
  35043. };
  35044. /**
  35045. * Gets a boolean indicating if specific vertex buffer is present
  35046. * @param kind defines the data kind (Position, normal, etc...)
  35047. * @returns true if data is present
  35048. */
  35049. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35050. if (!this._vertexBuffers) {
  35051. if (this._delayInfo) {
  35052. return this._delayInfo.indexOf(kind) !== -1;
  35053. }
  35054. return false;
  35055. }
  35056. return this._vertexBuffers[kind] !== undefined;
  35057. };
  35058. /**
  35059. * Gets a list of all attached data kinds (Position, normal, etc...)
  35060. * @returns a list of string containing all kinds
  35061. */
  35062. Geometry.prototype.getVerticesDataKinds = function () {
  35063. var result = [];
  35064. var kind;
  35065. if (!this._vertexBuffers && this._delayInfo) {
  35066. for (kind in this._delayInfo) {
  35067. result.push(kind);
  35068. }
  35069. }
  35070. else {
  35071. for (kind in this._vertexBuffers) {
  35072. result.push(kind);
  35073. }
  35074. }
  35075. return result;
  35076. };
  35077. /**
  35078. * Update index buffer
  35079. * @param indices defines the indices to store in the index buffer
  35080. * @param offset defines the offset in the target buffer where to store the data
  35081. */
  35082. Geometry.prototype.updateIndices = function (indices, offset) {
  35083. if (!this._indexBuffer) {
  35084. return;
  35085. }
  35086. if (!this._indexBufferIsUpdatable) {
  35087. this.setIndices(indices, null, true);
  35088. }
  35089. else {
  35090. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35091. }
  35092. };
  35093. /**
  35094. * Creates a new index buffer
  35095. * @param indices defines the indices to store in the index buffer
  35096. * @param totalVertices defines the total number of vertices (could be null)
  35097. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35098. */
  35099. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35100. if (totalVertices === void 0) { totalVertices = null; }
  35101. if (updatable === void 0) { updatable = false; }
  35102. if (this._indexBuffer) {
  35103. this._engine._releaseBuffer(this._indexBuffer);
  35104. }
  35105. this._disposeVertexArrayObjects();
  35106. this._indices = indices;
  35107. this._indexBufferIsUpdatable = updatable;
  35108. if (this._meshes.length !== 0 && this._indices) {
  35109. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35110. }
  35111. if (totalVertices != undefined) {
  35112. this._totalVertices = totalVertices;
  35113. }
  35114. var meshes = this._meshes;
  35115. var numOfMeshes = meshes.length;
  35116. for (var index = 0; index < numOfMeshes; index++) {
  35117. meshes[index]._createGlobalSubMesh(true);
  35118. }
  35119. this.notifyUpdate();
  35120. };
  35121. /**
  35122. * Return the total number of indices
  35123. * @returns the total number of indices
  35124. */
  35125. Geometry.prototype.getTotalIndices = function () {
  35126. if (!this.isReady()) {
  35127. return 0;
  35128. }
  35129. return this._indices.length;
  35130. };
  35131. /**
  35132. * Gets the index buffer array
  35133. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35134. * @returns the index buffer array
  35135. */
  35136. Geometry.prototype.getIndices = function (copyWhenShared) {
  35137. if (!this.isReady()) {
  35138. return null;
  35139. }
  35140. var orig = this._indices;
  35141. if (!copyWhenShared || this._meshes.length === 1) {
  35142. return orig;
  35143. }
  35144. else {
  35145. var len = orig.length;
  35146. var copy = [];
  35147. for (var i = 0; i < len; i++) {
  35148. copy.push(orig[i]);
  35149. }
  35150. return copy;
  35151. }
  35152. };
  35153. /**
  35154. * Gets the index buffer
  35155. * @return the index buffer
  35156. */
  35157. Geometry.prototype.getIndexBuffer = function () {
  35158. if (!this.isReady()) {
  35159. return null;
  35160. }
  35161. return this._indexBuffer;
  35162. };
  35163. /** @ignore */
  35164. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35165. if (effect === void 0) { effect = null; }
  35166. if (!effect || !this._vertexArrayObjects) {
  35167. return;
  35168. }
  35169. if (this._vertexArrayObjects[effect.key]) {
  35170. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35171. delete this._vertexArrayObjects[effect.key];
  35172. }
  35173. };
  35174. /**
  35175. * Release the associated resources for a specific mesh
  35176. * @param mesh defines the source mesh
  35177. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35178. */
  35179. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35180. var meshes = this._meshes;
  35181. var index = meshes.indexOf(mesh);
  35182. if (index === -1) {
  35183. return;
  35184. }
  35185. meshes.splice(index, 1);
  35186. mesh._geometry = null;
  35187. if (meshes.length === 0 && shouldDispose) {
  35188. this.dispose();
  35189. }
  35190. };
  35191. /**
  35192. * Apply current geometry to a given mesh
  35193. * @param mesh defines the mesh to apply geometry to
  35194. */
  35195. Geometry.prototype.applyToMesh = function (mesh) {
  35196. if (mesh._geometry === this) {
  35197. return;
  35198. }
  35199. var previousGeometry = mesh._geometry;
  35200. if (previousGeometry) {
  35201. previousGeometry.releaseForMesh(mesh);
  35202. }
  35203. var meshes = this._meshes;
  35204. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35205. mesh._geometry = this;
  35206. this._scene.pushGeometry(this);
  35207. meshes.push(mesh);
  35208. if (this.isReady()) {
  35209. this._applyToMesh(mesh);
  35210. }
  35211. else {
  35212. mesh._boundingInfo = this._boundingInfo;
  35213. }
  35214. };
  35215. Geometry.prototype.updateExtend = function (data, stride) {
  35216. if (data === void 0) { data = null; }
  35217. if (!data) {
  35218. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35219. }
  35220. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35221. };
  35222. Geometry.prototype._applyToMesh = function (mesh) {
  35223. var numOfMeshes = this._meshes.length;
  35224. // vertexBuffers
  35225. for (var kind in this._vertexBuffers) {
  35226. if (numOfMeshes === 1) {
  35227. this._vertexBuffers[kind].create();
  35228. }
  35229. var buffer = this._vertexBuffers[kind].getBuffer();
  35230. if (buffer)
  35231. buffer.references = numOfMeshes;
  35232. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35233. if (!this._extend) {
  35234. this.updateExtend(this._vertexBuffers[kind].getData());
  35235. }
  35236. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35237. mesh._createGlobalSubMesh(false);
  35238. //bounding info was just created again, world matrix should be applied again.
  35239. mesh._updateBoundingInfo();
  35240. }
  35241. }
  35242. // indexBuffer
  35243. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35244. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35245. }
  35246. if (this._indexBuffer) {
  35247. this._indexBuffer.references = numOfMeshes;
  35248. }
  35249. };
  35250. Geometry.prototype.notifyUpdate = function (kind) {
  35251. if (this.onGeometryUpdated) {
  35252. this.onGeometryUpdated(this, kind);
  35253. }
  35254. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35255. var mesh = _a[_i];
  35256. mesh._markSubMeshesAsAttributesDirty();
  35257. }
  35258. };
  35259. /**
  35260. * Load the geometry if it was flagged as delay loaded
  35261. * @param scene defines the hosting scene
  35262. * @param onLoaded defines a callback called when the geometry is loaded
  35263. */
  35264. Geometry.prototype.load = function (scene, onLoaded) {
  35265. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35266. return;
  35267. }
  35268. if (this.isReady()) {
  35269. if (onLoaded) {
  35270. onLoaded();
  35271. }
  35272. return;
  35273. }
  35274. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35275. this._queueLoad(scene, onLoaded);
  35276. };
  35277. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35278. var _this = this;
  35279. if (!this.delayLoadingFile) {
  35280. return;
  35281. }
  35282. scene._addPendingData(this);
  35283. scene._loadFile(this.delayLoadingFile, function (data) {
  35284. if (!_this._delayLoadingFunction) {
  35285. return;
  35286. }
  35287. _this._delayLoadingFunction(JSON.parse(data), _this);
  35288. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35289. _this._delayInfo = [];
  35290. scene._removePendingData(_this);
  35291. var meshes = _this._meshes;
  35292. var numOfMeshes = meshes.length;
  35293. for (var index = 0; index < numOfMeshes; index++) {
  35294. _this._applyToMesh(meshes[index]);
  35295. }
  35296. if (onLoaded) {
  35297. onLoaded();
  35298. }
  35299. }, undefined, true);
  35300. };
  35301. /**
  35302. * Invert the geometry to move from a right handed system to a left handed one.
  35303. */
  35304. Geometry.prototype.toLeftHanded = function () {
  35305. // Flip faces
  35306. var tIndices = this.getIndices(false);
  35307. if (tIndices != null && tIndices.length > 0) {
  35308. for (var i = 0; i < tIndices.length; i += 3) {
  35309. var tTemp = tIndices[i + 0];
  35310. tIndices[i + 0] = tIndices[i + 2];
  35311. tIndices[i + 2] = tTemp;
  35312. }
  35313. this.setIndices(tIndices);
  35314. }
  35315. // Negate position.z
  35316. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35317. if (tPositions != null && tPositions.length > 0) {
  35318. for (var i = 0; i < tPositions.length; i += 3) {
  35319. tPositions[i + 2] = -tPositions[i + 2];
  35320. }
  35321. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35322. }
  35323. // Negate normal.z
  35324. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35325. if (tNormals != null && tNormals.length > 0) {
  35326. for (var i = 0; i < tNormals.length; i += 3) {
  35327. tNormals[i + 2] = -tNormals[i + 2];
  35328. }
  35329. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35330. }
  35331. };
  35332. // Cache
  35333. /** @ignore */
  35334. Geometry.prototype._resetPointsArrayCache = function () {
  35335. this._positions = null;
  35336. };
  35337. /** @ignore */
  35338. Geometry.prototype._generatePointsArray = function () {
  35339. if (this._positions)
  35340. return true;
  35341. this._positions = [];
  35342. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35343. if (!data) {
  35344. return false;
  35345. }
  35346. for (var index = 0; index < data.length; index += 3) {
  35347. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35348. }
  35349. return true;
  35350. };
  35351. /**
  35352. * Gets a value indicating if the geometry is disposed
  35353. * @returns true if the geometry was disposed
  35354. */
  35355. Geometry.prototype.isDisposed = function () {
  35356. return this._isDisposed;
  35357. };
  35358. Geometry.prototype._disposeVertexArrayObjects = function () {
  35359. if (this._vertexArrayObjects) {
  35360. for (var kind in this._vertexArrayObjects) {
  35361. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35362. }
  35363. this._vertexArrayObjects = {};
  35364. }
  35365. };
  35366. /**
  35367. * Free all associated resources
  35368. */
  35369. Geometry.prototype.dispose = function () {
  35370. var meshes = this._meshes;
  35371. var numOfMeshes = meshes.length;
  35372. var index;
  35373. for (index = 0; index < numOfMeshes; index++) {
  35374. this.releaseForMesh(meshes[index]);
  35375. }
  35376. this._meshes = [];
  35377. this._disposeVertexArrayObjects();
  35378. for (var kind in this._vertexBuffers) {
  35379. this._vertexBuffers[kind].dispose();
  35380. }
  35381. this._vertexBuffers = {};
  35382. this._totalVertices = 0;
  35383. if (this._indexBuffer) {
  35384. this._engine._releaseBuffer(this._indexBuffer);
  35385. }
  35386. this._indexBuffer = null;
  35387. this._indices = [];
  35388. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35389. this.delayLoadingFile = null;
  35390. this._delayLoadingFunction = null;
  35391. this._delayInfo = [];
  35392. this._boundingInfo = null;
  35393. this._scene.removeGeometry(this);
  35394. this._isDisposed = true;
  35395. };
  35396. /**
  35397. * Clone the current geometry into a new geometry
  35398. * @param id defines the unique ID of the new geometry
  35399. * @returns a new geometry object
  35400. */
  35401. Geometry.prototype.copy = function (id) {
  35402. var vertexData = new BABYLON.VertexData();
  35403. vertexData.indices = [];
  35404. var indices = this.getIndices();
  35405. if (indices) {
  35406. for (var index = 0; index < indices.length; index++) {
  35407. vertexData.indices.push(indices[index]);
  35408. }
  35409. }
  35410. var updatable = false;
  35411. var stopChecking = false;
  35412. var kind;
  35413. for (kind in this._vertexBuffers) {
  35414. // using slice() to make a copy of the array and not just reference it
  35415. var data = this.getVerticesData(kind);
  35416. if (data instanceof Float32Array) {
  35417. vertexData.set(new Float32Array(data), kind);
  35418. }
  35419. else {
  35420. vertexData.set(data.slice(0), kind);
  35421. }
  35422. if (!stopChecking) {
  35423. var vb = this.getVertexBuffer(kind);
  35424. if (vb) {
  35425. updatable = vb.isUpdatable();
  35426. stopChecking = !updatable;
  35427. }
  35428. }
  35429. }
  35430. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35431. geometry.delayLoadState = this.delayLoadState;
  35432. geometry.delayLoadingFile = this.delayLoadingFile;
  35433. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35434. for (kind in this._delayInfo) {
  35435. geometry._delayInfo = geometry._delayInfo || [];
  35436. geometry._delayInfo.push(kind);
  35437. }
  35438. // Bounding info
  35439. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35440. return geometry;
  35441. };
  35442. /**
  35443. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35444. * @return a JSON representation of the current geometry data (without the vertices data)
  35445. */
  35446. Geometry.prototype.serialize = function () {
  35447. var serializationObject = {};
  35448. serializationObject.id = this.id;
  35449. serializationObject.updatable = this._updatable;
  35450. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35451. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35452. }
  35453. return serializationObject;
  35454. };
  35455. Geometry.prototype.toNumberArray = function (origin) {
  35456. if (Array.isArray(origin)) {
  35457. return origin;
  35458. }
  35459. else {
  35460. return Array.prototype.slice.call(origin);
  35461. }
  35462. };
  35463. /**
  35464. * Serialize all vertices data into a JSON oject
  35465. * @returns a JSON representation of the current geometry data
  35466. */
  35467. Geometry.prototype.serializeVerticeData = function () {
  35468. var serializationObject = this.serialize();
  35469. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35470. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35471. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35472. serializationObject.positions._updatable = true;
  35473. }
  35474. }
  35475. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35476. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35477. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35478. serializationObject.normals._updatable = true;
  35479. }
  35480. }
  35481. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35482. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35483. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35484. serializationObject.tangets._updatable = true;
  35485. }
  35486. }
  35487. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35488. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35489. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35490. serializationObject.uvs._updatable = true;
  35491. }
  35492. }
  35493. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35494. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35495. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35496. serializationObject.uv2s._updatable = true;
  35497. }
  35498. }
  35499. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35500. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35501. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35502. serializationObject.uv3s._updatable = true;
  35503. }
  35504. }
  35505. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35506. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35507. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35508. serializationObject.uv4s._updatable = true;
  35509. }
  35510. }
  35511. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35512. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35513. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35514. serializationObject.uv5s._updatable = true;
  35515. }
  35516. }
  35517. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35518. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35519. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35520. serializationObject.uv6s._updatable = true;
  35521. }
  35522. }
  35523. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35524. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35525. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35526. serializationObject.colors._updatable = true;
  35527. }
  35528. }
  35529. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35530. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35531. serializationObject.matricesIndices._isExpanded = true;
  35532. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35533. serializationObject.matricesIndices._updatable = true;
  35534. }
  35535. }
  35536. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35537. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35538. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35539. serializationObject.matricesWeights._updatable = true;
  35540. }
  35541. }
  35542. serializationObject.indices = this.toNumberArray(this.getIndices());
  35543. return serializationObject;
  35544. };
  35545. // Statics
  35546. /**
  35547. * Extracts a clone of a mesh geometry
  35548. * @param mesh defines the source mesh
  35549. * @param id defines the unique ID of the new geometry object
  35550. * @returns the new geometry object
  35551. */
  35552. Geometry.ExtractFromMesh = function (mesh, id) {
  35553. var geometry = mesh._geometry;
  35554. if (!geometry) {
  35555. return null;
  35556. }
  35557. return geometry.copy(id);
  35558. };
  35559. /**
  35560. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35561. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35562. * Be aware Math.random() could cause collisions, but:
  35563. * "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"
  35564. * @returns a string containing a new GUID
  35565. */
  35566. Geometry.RandomId = function () {
  35567. return BABYLON.Tools.RandomId();
  35568. };
  35569. /** @ignore */
  35570. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35571. var scene = mesh.getScene();
  35572. // Geometry
  35573. var geometryId = parsedGeometry.geometryId;
  35574. if (geometryId) {
  35575. var geometry = scene.getGeometryByID(geometryId);
  35576. if (geometry) {
  35577. geometry.applyToMesh(mesh);
  35578. }
  35579. }
  35580. else if (parsedGeometry instanceof ArrayBuffer) {
  35581. var binaryInfo = mesh._binaryInfo;
  35582. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35583. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35584. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35585. }
  35586. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35587. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35588. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35589. }
  35590. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35591. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35592. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35593. }
  35594. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35595. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35596. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35597. }
  35598. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35599. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35600. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35601. }
  35602. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35603. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35604. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35605. }
  35606. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35607. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35608. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35609. }
  35610. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35611. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35612. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35613. }
  35614. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35615. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35616. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35617. }
  35618. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35619. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35620. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35621. }
  35622. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35623. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35624. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35625. }
  35626. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35627. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35628. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35629. }
  35630. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35631. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35632. mesh.setIndices(indicesData, null);
  35633. }
  35634. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35635. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35636. mesh.subMeshes = [];
  35637. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35638. var materialIndex = subMeshesData[(i * 5) + 0];
  35639. var verticesStart = subMeshesData[(i * 5) + 1];
  35640. var verticesCount = subMeshesData[(i * 5) + 2];
  35641. var indexStart = subMeshesData[(i * 5) + 3];
  35642. var indexCount = subMeshesData[(i * 5) + 4];
  35643. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35644. }
  35645. }
  35646. }
  35647. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35648. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35649. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35650. if (parsedGeometry.tangents) {
  35651. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35652. }
  35653. if (parsedGeometry.uvs) {
  35654. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35655. }
  35656. if (parsedGeometry.uvs2) {
  35657. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35658. }
  35659. if (parsedGeometry.uvs3) {
  35660. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35661. }
  35662. if (parsedGeometry.uvs4) {
  35663. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35664. }
  35665. if (parsedGeometry.uvs5) {
  35666. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35667. }
  35668. if (parsedGeometry.uvs6) {
  35669. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35670. }
  35671. if (parsedGeometry.colors) {
  35672. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35673. }
  35674. if (parsedGeometry.matricesIndices) {
  35675. if (!parsedGeometry.matricesIndices._isExpanded) {
  35676. var floatIndices = [];
  35677. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35678. var matricesIndex = parsedGeometry.matricesIndices[i];
  35679. floatIndices.push(matricesIndex & 0x000000FF);
  35680. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35681. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35682. floatIndices.push(matricesIndex >> 24);
  35683. }
  35684. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35685. }
  35686. else {
  35687. delete parsedGeometry.matricesIndices._isExpanded;
  35688. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35689. }
  35690. }
  35691. if (parsedGeometry.matricesIndicesExtra) {
  35692. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35693. var floatIndices = [];
  35694. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35695. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35696. floatIndices.push(matricesIndex & 0x000000FF);
  35697. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35698. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35699. floatIndices.push(matricesIndex >> 24);
  35700. }
  35701. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35702. }
  35703. else {
  35704. delete parsedGeometry.matricesIndices._isExpanded;
  35705. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35706. }
  35707. }
  35708. if (parsedGeometry.matricesWeights) {
  35709. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35710. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35711. }
  35712. if (parsedGeometry.matricesWeightsExtra) {
  35713. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35714. }
  35715. mesh.setIndices(parsedGeometry.indices, null);
  35716. }
  35717. // SubMeshes
  35718. if (parsedGeometry.subMeshes) {
  35719. mesh.subMeshes = [];
  35720. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35721. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35722. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35723. }
  35724. }
  35725. // Flat shading
  35726. if (mesh._shouldGenerateFlatShading) {
  35727. mesh.convertToFlatShadedMesh();
  35728. delete mesh._shouldGenerateFlatShading;
  35729. }
  35730. // Update
  35731. mesh.computeWorldMatrix(true);
  35732. // Octree
  35733. var sceneOctree = scene.selectionOctree;
  35734. if (sceneOctree !== undefined && sceneOctree !== null) {
  35735. sceneOctree.addMesh(mesh);
  35736. }
  35737. };
  35738. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35739. var epsilon = 1e-3;
  35740. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35741. return;
  35742. }
  35743. var noInfluenceBoneIndex = 0.0;
  35744. if (parsedGeometry.skeletonId > -1) {
  35745. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35746. if (!skeleton) {
  35747. return;
  35748. }
  35749. noInfluenceBoneIndex = skeleton.bones.length;
  35750. }
  35751. else {
  35752. return;
  35753. }
  35754. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35755. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35756. var matricesWeights = parsedGeometry.matricesWeights;
  35757. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35758. var influencers = parsedGeometry.numBoneInfluencer;
  35759. var size = matricesWeights.length;
  35760. for (var i = 0; i < size; i += 4) {
  35761. var weight = 0.0;
  35762. var firstZeroWeight = -1;
  35763. for (var j = 0; j < 4; j++) {
  35764. var w = matricesWeights[i + j];
  35765. weight += w;
  35766. if (w < epsilon && firstZeroWeight < 0) {
  35767. firstZeroWeight = j;
  35768. }
  35769. }
  35770. if (matricesWeightsExtra) {
  35771. for (var j = 0; j < 4; j++) {
  35772. var w = matricesWeightsExtra[i + j];
  35773. weight += w;
  35774. if (w < epsilon && firstZeroWeight < 0) {
  35775. firstZeroWeight = j + 4;
  35776. }
  35777. }
  35778. }
  35779. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35780. firstZeroWeight = influencers - 1;
  35781. }
  35782. if (weight > epsilon) {
  35783. var mweight = 1.0 / weight;
  35784. for (var j = 0; j < 4; j++) {
  35785. matricesWeights[i + j] *= mweight;
  35786. }
  35787. if (matricesWeightsExtra) {
  35788. for (var j = 0; j < 4; j++) {
  35789. matricesWeightsExtra[i + j] *= mweight;
  35790. }
  35791. }
  35792. }
  35793. else {
  35794. if (firstZeroWeight >= 4) {
  35795. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35796. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35797. }
  35798. else {
  35799. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35800. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35801. }
  35802. }
  35803. }
  35804. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35805. if (parsedGeometry.matricesWeightsExtra) {
  35806. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35807. }
  35808. };
  35809. /**
  35810. * Create a new geometry from persisted data (Using .babylon file format)
  35811. * @param parsedVertexData defines the persisted data
  35812. * @param scene defines the hosting scene
  35813. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35814. * @returns the new geometry object
  35815. */
  35816. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35817. if (scene.getGeometryByID(parsedVertexData.id)) {
  35818. return null; // null since geometry could be something else than a box...
  35819. }
  35820. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35821. if (BABYLON.Tags) {
  35822. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35823. }
  35824. if (parsedVertexData.delayLoadingFile) {
  35825. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35826. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35827. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35828. geometry._delayInfo = [];
  35829. if (parsedVertexData.hasUVs) {
  35830. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35831. }
  35832. if (parsedVertexData.hasUVs2) {
  35833. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35834. }
  35835. if (parsedVertexData.hasUVs3) {
  35836. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35837. }
  35838. if (parsedVertexData.hasUVs4) {
  35839. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35840. }
  35841. if (parsedVertexData.hasUVs5) {
  35842. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35843. }
  35844. if (parsedVertexData.hasUVs6) {
  35845. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35846. }
  35847. if (parsedVertexData.hasColors) {
  35848. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35849. }
  35850. if (parsedVertexData.hasMatricesIndices) {
  35851. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35852. }
  35853. if (parsedVertexData.hasMatricesWeights) {
  35854. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35855. }
  35856. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35857. }
  35858. else {
  35859. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35860. }
  35861. scene.pushGeometry(geometry, true);
  35862. return geometry;
  35863. };
  35864. return Geometry;
  35865. }());
  35866. BABYLON.Geometry = Geometry;
  35867. // Primitives
  35868. /// Abstract class
  35869. /**
  35870. * Abstract class used to provide common services for all typed geometries
  35871. */
  35872. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35873. __extends(_PrimitiveGeometry, _super);
  35874. /**
  35875. * Creates a new typed geometry
  35876. * @param id defines the unique ID of the geometry
  35877. * @param scene defines the hosting scene
  35878. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35879. * @param mesh defines the hosting mesh (can be null)
  35880. */
  35881. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35882. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35883. if (mesh === void 0) { mesh = null; }
  35884. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35885. _this._canBeRegenerated = _canBeRegenerated;
  35886. _this._beingRegenerated = true;
  35887. _this.regenerate();
  35888. _this._beingRegenerated = false;
  35889. return _this;
  35890. }
  35891. /**
  35892. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35893. * @returns true if the geometry can be regenerated
  35894. */
  35895. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35896. return this._canBeRegenerated;
  35897. };
  35898. /**
  35899. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35900. */
  35901. _PrimitiveGeometry.prototype.regenerate = function () {
  35902. if (!this._canBeRegenerated) {
  35903. return;
  35904. }
  35905. this._beingRegenerated = true;
  35906. this.setAllVerticesData(this._regenerateVertexData(), false);
  35907. this._beingRegenerated = false;
  35908. };
  35909. /**
  35910. * Clone the geometry
  35911. * @param id defines the unique ID of the new geometry
  35912. * @returns the new geometry
  35913. */
  35914. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35915. return _super.prototype.copy.call(this, id);
  35916. };
  35917. // overrides
  35918. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35919. if (!this._beingRegenerated) {
  35920. return;
  35921. }
  35922. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35923. };
  35924. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35925. if (!this._beingRegenerated) {
  35926. return;
  35927. }
  35928. _super.prototype.setVerticesData.call(this, kind, data, false);
  35929. };
  35930. // to override
  35931. /** @ignore */
  35932. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35933. throw new Error("Abstract method");
  35934. };
  35935. _PrimitiveGeometry.prototype.copy = function (id) {
  35936. throw new Error("Must be overriden in sub-classes.");
  35937. };
  35938. _PrimitiveGeometry.prototype.serialize = function () {
  35939. var serializationObject = _super.prototype.serialize.call(this);
  35940. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35941. return serializationObject;
  35942. };
  35943. return _PrimitiveGeometry;
  35944. }(Geometry));
  35945. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35946. /**
  35947. * Creates a ribbon geometry
  35948. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35949. */
  35950. var RibbonGeometry = /** @class */ (function (_super) {
  35951. __extends(RibbonGeometry, _super);
  35952. /**
  35953. * Creates a ribbon geometry
  35954. * @param id defines the unique ID of the geometry
  35955. * @param scene defines the hosting scene
  35956. * @param pathArray defines the array of paths to use
  35957. * @param closeArray defines if the last path and the first path must be joined
  35958. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35959. * @param offset defines the offset between points
  35960. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35961. * @param mesh defines the hosting mesh (can be null)
  35962. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35963. */
  35964. function RibbonGeometry(id, scene,
  35965. /**
  35966. * Defines the array of paths to use
  35967. */
  35968. pathArray,
  35969. /**
  35970. * Defines if the last and first points of each path in your pathArray must be joined
  35971. */
  35972. closeArray,
  35973. /**
  35974. * Defines if the last and first points of each path in your pathArray must be joined
  35975. */
  35976. closePath,
  35977. /**
  35978. * Defines the offset between points
  35979. */
  35980. offset, canBeRegenerated, mesh,
  35981. /**
  35982. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35983. */
  35984. side) {
  35985. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35986. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35987. _this.pathArray = pathArray;
  35988. _this.closeArray = closeArray;
  35989. _this.closePath = closePath;
  35990. _this.offset = offset;
  35991. _this.side = side;
  35992. return _this;
  35993. }
  35994. /** @ignore */
  35995. RibbonGeometry.prototype._regenerateVertexData = function () {
  35996. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35997. };
  35998. RibbonGeometry.prototype.copy = function (id) {
  35999. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36000. };
  36001. return RibbonGeometry;
  36002. }(_PrimitiveGeometry));
  36003. BABYLON.RibbonGeometry = RibbonGeometry;
  36004. /**
  36005. * Creates a box geometry
  36006. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36007. */
  36008. var BoxGeometry = /** @class */ (function (_super) {
  36009. __extends(BoxGeometry, _super);
  36010. /**
  36011. * Creates a box geometry
  36012. * @param id defines the unique ID of the geometry
  36013. * @param scene defines the hosting scene
  36014. * @param size defines the zise of the box (width, height and depth are the same)
  36015. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36016. * @param mesh defines the hosting mesh (can be null)
  36017. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36018. */
  36019. function BoxGeometry(id, scene,
  36020. /**
  36021. * Defines the zise of the box (width, height and depth are the same)
  36022. */
  36023. size, canBeRegenerated, mesh,
  36024. /**
  36025. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36026. */
  36027. side) {
  36028. if (mesh === void 0) { mesh = null; }
  36029. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36030. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36031. _this.size = size;
  36032. _this.side = side;
  36033. return _this;
  36034. }
  36035. BoxGeometry.prototype._regenerateVertexData = function () {
  36036. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36037. };
  36038. BoxGeometry.prototype.copy = function (id) {
  36039. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36040. };
  36041. BoxGeometry.prototype.serialize = function () {
  36042. var serializationObject = _super.prototype.serialize.call(this);
  36043. serializationObject.size = this.size;
  36044. return serializationObject;
  36045. };
  36046. BoxGeometry.Parse = function (parsedBox, scene) {
  36047. if (scene.getGeometryByID(parsedBox.id)) {
  36048. return null; // null since geometry could be something else than a box...
  36049. }
  36050. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36051. if (BABYLON.Tags) {
  36052. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36053. }
  36054. scene.pushGeometry(box, true);
  36055. return box;
  36056. };
  36057. return BoxGeometry;
  36058. }(_PrimitiveGeometry));
  36059. BABYLON.BoxGeometry = BoxGeometry;
  36060. /**
  36061. * Creates a sphere geometry
  36062. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36063. */
  36064. var SphereGeometry = /** @class */ (function (_super) {
  36065. __extends(SphereGeometry, _super);
  36066. /**
  36067. * Create a new sphere geometry
  36068. * @param id defines the unique ID of the geometry
  36069. * @param scene defines the hosting scene
  36070. * @param segments defines the number of segments to use to create the sphere
  36071. * @param diameter defines the diameter of the sphere
  36072. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36073. * @param mesh defines the hosting mesh (can be null)
  36074. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36075. */
  36076. function SphereGeometry(id, scene,
  36077. /**
  36078. * Defines the number of segments to use to create the sphere
  36079. */
  36080. segments,
  36081. /**
  36082. * Defines the diameter of the sphere
  36083. */
  36084. diameter, canBeRegenerated, mesh,
  36085. /**
  36086. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36087. */
  36088. side) {
  36089. if (mesh === void 0) { mesh = null; }
  36090. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36091. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36092. _this.segments = segments;
  36093. _this.diameter = diameter;
  36094. _this.side = side;
  36095. return _this;
  36096. }
  36097. SphereGeometry.prototype._regenerateVertexData = function () {
  36098. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36099. };
  36100. SphereGeometry.prototype.copy = function (id) {
  36101. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36102. };
  36103. SphereGeometry.prototype.serialize = function () {
  36104. var serializationObject = _super.prototype.serialize.call(this);
  36105. serializationObject.segments = this.segments;
  36106. serializationObject.diameter = this.diameter;
  36107. return serializationObject;
  36108. };
  36109. SphereGeometry.Parse = function (parsedSphere, scene) {
  36110. if (scene.getGeometryByID(parsedSphere.id)) {
  36111. return null; // null since geometry could be something else than a sphere...
  36112. }
  36113. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36114. if (BABYLON.Tags) {
  36115. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36116. }
  36117. scene.pushGeometry(sphere, true);
  36118. return sphere;
  36119. };
  36120. return SphereGeometry;
  36121. }(_PrimitiveGeometry));
  36122. BABYLON.SphereGeometry = SphereGeometry;
  36123. /**
  36124. * Creates a disc geometry
  36125. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36126. */
  36127. var DiscGeometry = /** @class */ (function (_super) {
  36128. __extends(DiscGeometry, _super);
  36129. /**
  36130. * Creates a new disc geometry
  36131. * @param id defines the unique ID of the geometry
  36132. * @param scene defines the hosting scene
  36133. * @param radius defines the radius of the disc
  36134. * @param tessellation defines the tesselation factor to apply to the disc
  36135. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36136. * @param mesh defines the hosting mesh (can be null)
  36137. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36138. */
  36139. function DiscGeometry(id, scene,
  36140. /**
  36141. * Defines the radius of the disc
  36142. */
  36143. radius,
  36144. /**
  36145. * Defines the tesselation factor to apply to the disc
  36146. */
  36147. tessellation, canBeRegenerated, mesh,
  36148. /**
  36149. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36150. */
  36151. side) {
  36152. if (mesh === void 0) { mesh = null; }
  36153. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36154. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36155. _this.radius = radius;
  36156. _this.tessellation = tessellation;
  36157. _this.side = side;
  36158. return _this;
  36159. }
  36160. DiscGeometry.prototype._regenerateVertexData = function () {
  36161. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36162. };
  36163. DiscGeometry.prototype.copy = function (id) {
  36164. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36165. };
  36166. return DiscGeometry;
  36167. }(_PrimitiveGeometry));
  36168. BABYLON.DiscGeometry = DiscGeometry;
  36169. /**
  36170. * Creates a new cylinder geometry
  36171. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36172. */
  36173. var CylinderGeometry = /** @class */ (function (_super) {
  36174. __extends(CylinderGeometry, _super);
  36175. /**
  36176. * Creates a new cylinder geometry
  36177. * @param id defines the unique ID of the geometry
  36178. * @param scene defines the hosting scene
  36179. * @param height defines the height of the cylinder
  36180. * @param diameterTop defines the diameter of the cylinder's top cap
  36181. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36182. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36183. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36184. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36185. * @param mesh defines the hosting mesh (can be null)
  36186. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36187. */
  36188. function CylinderGeometry(id, scene,
  36189. /**
  36190. * Defines the height of the cylinder
  36191. */
  36192. height,
  36193. /**
  36194. * Defines the diameter of the cylinder's top cap
  36195. */
  36196. diameterTop,
  36197. /**
  36198. * Defines the diameter of the cylinder's bottom cap
  36199. */
  36200. diameterBottom,
  36201. /**
  36202. * Defines the tessellation factor to apply to the cylinder
  36203. */
  36204. tessellation,
  36205. /**
  36206. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36207. */
  36208. subdivisions, canBeRegenerated, mesh,
  36209. /**
  36210. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36211. */
  36212. side) {
  36213. if (subdivisions === void 0) { subdivisions = 1; }
  36214. if (mesh === void 0) { mesh = null; }
  36215. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36216. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36217. _this.height = height;
  36218. _this.diameterTop = diameterTop;
  36219. _this.diameterBottom = diameterBottom;
  36220. _this.tessellation = tessellation;
  36221. _this.subdivisions = subdivisions;
  36222. _this.side = side;
  36223. return _this;
  36224. }
  36225. CylinderGeometry.prototype._regenerateVertexData = function () {
  36226. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36227. };
  36228. CylinderGeometry.prototype.copy = function (id) {
  36229. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36230. };
  36231. CylinderGeometry.prototype.serialize = function () {
  36232. var serializationObject = _super.prototype.serialize.call(this);
  36233. serializationObject.height = this.height;
  36234. serializationObject.diameterTop = this.diameterTop;
  36235. serializationObject.diameterBottom = this.diameterBottom;
  36236. serializationObject.tessellation = this.tessellation;
  36237. return serializationObject;
  36238. };
  36239. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36240. if (scene.getGeometryByID(parsedCylinder.id)) {
  36241. return null; // null since geometry could be something else than a cylinder...
  36242. }
  36243. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36244. if (BABYLON.Tags) {
  36245. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36246. }
  36247. scene.pushGeometry(cylinder, true);
  36248. return cylinder;
  36249. };
  36250. return CylinderGeometry;
  36251. }(_PrimitiveGeometry));
  36252. BABYLON.CylinderGeometry = CylinderGeometry;
  36253. /**
  36254. * Creates a new torus geometry
  36255. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36256. */
  36257. var TorusGeometry = /** @class */ (function (_super) {
  36258. __extends(TorusGeometry, _super);
  36259. /**
  36260. * Creates a new torus geometry
  36261. * @param id defines the unique ID of the geometry
  36262. * @param scene defines the hosting scene
  36263. * @param diameter defines the diameter of the torus
  36264. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36265. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36266. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36267. * @param mesh defines the hosting mesh (can be null)
  36268. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36269. */
  36270. function TorusGeometry(id, scene,
  36271. /**
  36272. * Defines the diameter of the torus
  36273. */
  36274. diameter,
  36275. /**
  36276. * Defines the thickness of the torus (ie. internal diameter)
  36277. */
  36278. thickness,
  36279. /**
  36280. * Defines the tesselation factor to apply to the torus
  36281. */
  36282. tessellation, canBeRegenerated, mesh,
  36283. /**
  36284. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36285. */
  36286. side) {
  36287. if (mesh === void 0) { mesh = null; }
  36288. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36289. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36290. _this.diameter = diameter;
  36291. _this.thickness = thickness;
  36292. _this.tessellation = tessellation;
  36293. _this.side = side;
  36294. return _this;
  36295. }
  36296. TorusGeometry.prototype._regenerateVertexData = function () {
  36297. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36298. };
  36299. TorusGeometry.prototype.copy = function (id) {
  36300. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36301. };
  36302. TorusGeometry.prototype.serialize = function () {
  36303. var serializationObject = _super.prototype.serialize.call(this);
  36304. serializationObject.diameter = this.diameter;
  36305. serializationObject.thickness = this.thickness;
  36306. serializationObject.tessellation = this.tessellation;
  36307. return serializationObject;
  36308. };
  36309. TorusGeometry.Parse = function (parsedTorus, scene) {
  36310. if (scene.getGeometryByID(parsedTorus.id)) {
  36311. return null; // null since geometry could be something else than a torus...
  36312. }
  36313. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36314. if (BABYLON.Tags) {
  36315. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36316. }
  36317. scene.pushGeometry(torus, true);
  36318. return torus;
  36319. };
  36320. return TorusGeometry;
  36321. }(_PrimitiveGeometry));
  36322. BABYLON.TorusGeometry = TorusGeometry;
  36323. /**
  36324. * Creates a new ground geometry
  36325. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36326. */
  36327. var GroundGeometry = /** @class */ (function (_super) {
  36328. __extends(GroundGeometry, _super);
  36329. /**
  36330. * Creates a new ground geometry
  36331. * @param id defines the unique ID of the geometry
  36332. * @param scene defines the hosting scene
  36333. * @param width defines the width of the ground
  36334. * @param height defines the height of the ground
  36335. * @param subdivisions defines the subdivisions to apply to the ground
  36336. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36337. * @param mesh defines the hosting mesh (can be null)
  36338. */
  36339. function GroundGeometry(id, scene,
  36340. /**
  36341. * Defines the width of the ground
  36342. */
  36343. width,
  36344. /**
  36345. * Defines the height of the ground
  36346. */
  36347. height,
  36348. /**
  36349. * Defines the subdivisions to apply to the ground
  36350. */
  36351. subdivisions, canBeRegenerated, mesh) {
  36352. if (mesh === void 0) { mesh = null; }
  36353. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36354. _this.width = width;
  36355. _this.height = height;
  36356. _this.subdivisions = subdivisions;
  36357. return _this;
  36358. }
  36359. GroundGeometry.prototype._regenerateVertexData = function () {
  36360. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36361. };
  36362. GroundGeometry.prototype.copy = function (id) {
  36363. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36364. };
  36365. GroundGeometry.prototype.serialize = function () {
  36366. var serializationObject = _super.prototype.serialize.call(this);
  36367. serializationObject.width = this.width;
  36368. serializationObject.height = this.height;
  36369. serializationObject.subdivisions = this.subdivisions;
  36370. return serializationObject;
  36371. };
  36372. GroundGeometry.Parse = function (parsedGround, scene) {
  36373. if (scene.getGeometryByID(parsedGround.id)) {
  36374. return null; // null since geometry could be something else than a ground...
  36375. }
  36376. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36377. if (BABYLON.Tags) {
  36378. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36379. }
  36380. scene.pushGeometry(ground, true);
  36381. return ground;
  36382. };
  36383. return GroundGeometry;
  36384. }(_PrimitiveGeometry));
  36385. BABYLON.GroundGeometry = GroundGeometry;
  36386. /**
  36387. * Creates a tiled ground geometry
  36388. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36389. */
  36390. var TiledGroundGeometry = /** @class */ (function (_super) {
  36391. __extends(TiledGroundGeometry, _super);
  36392. /**
  36393. * Creates a tiled ground geometry
  36394. * @param id defines the unique ID of the geometry
  36395. * @param scene defines the hosting scene
  36396. * @param xmin defines the minimum value on X axis
  36397. * @param zmin defines the minimum value on Z axis
  36398. * @param xmax defines the maximum value on X axis
  36399. * @param zmax defines the maximum value on Z axis
  36400. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36401. * @param precision defines the precision to use when computing the tiles
  36402. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36403. * @param mesh defines the hosting mesh (can be null)
  36404. */
  36405. function TiledGroundGeometry(id, scene,
  36406. /**
  36407. * Defines the minimum value on X axis
  36408. */
  36409. xmin,
  36410. /**
  36411. * Defines the minimum value on Z axis
  36412. */
  36413. zmin,
  36414. /**
  36415. * Defines the maximum value on X axis
  36416. */
  36417. xmax,
  36418. /**
  36419. * Defines the maximum value on Z axis
  36420. */
  36421. zmax,
  36422. /**
  36423. * Defines the subdivisions to apply to the ground
  36424. */
  36425. subdivisions,
  36426. /**
  36427. * Defines the precision to use when computing the tiles
  36428. */
  36429. precision, canBeRegenerated, mesh) {
  36430. if (mesh === void 0) { mesh = null; }
  36431. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36432. _this.xmin = xmin;
  36433. _this.zmin = zmin;
  36434. _this.xmax = xmax;
  36435. _this.zmax = zmax;
  36436. _this.subdivisions = subdivisions;
  36437. _this.precision = precision;
  36438. return _this;
  36439. }
  36440. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36441. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36442. };
  36443. TiledGroundGeometry.prototype.copy = function (id) {
  36444. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36445. };
  36446. return TiledGroundGeometry;
  36447. }(_PrimitiveGeometry));
  36448. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36449. /**
  36450. * Creates a plane geometry
  36451. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36452. */
  36453. var PlaneGeometry = /** @class */ (function (_super) {
  36454. __extends(PlaneGeometry, _super);
  36455. /**
  36456. * Creates a plane geometry
  36457. * @param id defines the unique ID of the geometry
  36458. * @param scene defines the hosting scene
  36459. * @param size defines the size of the plane (width === height)
  36460. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36461. * @param mesh defines the hosting mesh (can be null)
  36462. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36463. */
  36464. function PlaneGeometry(id, scene,
  36465. /**
  36466. * Defines the size of the plane (width === height)
  36467. */
  36468. size, canBeRegenerated, mesh,
  36469. /**
  36470. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36471. */
  36472. side) {
  36473. if (mesh === void 0) { mesh = null; }
  36474. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36475. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36476. _this.size = size;
  36477. _this.side = side;
  36478. return _this;
  36479. }
  36480. PlaneGeometry.prototype._regenerateVertexData = function () {
  36481. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36482. };
  36483. PlaneGeometry.prototype.copy = function (id) {
  36484. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36485. };
  36486. PlaneGeometry.prototype.serialize = function () {
  36487. var serializationObject = _super.prototype.serialize.call(this);
  36488. serializationObject.size = this.size;
  36489. return serializationObject;
  36490. };
  36491. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36492. if (scene.getGeometryByID(parsedPlane.id)) {
  36493. return null; // null since geometry could be something else than a ground...
  36494. }
  36495. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36496. if (BABYLON.Tags) {
  36497. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36498. }
  36499. scene.pushGeometry(plane, true);
  36500. return plane;
  36501. };
  36502. return PlaneGeometry;
  36503. }(_PrimitiveGeometry));
  36504. BABYLON.PlaneGeometry = PlaneGeometry;
  36505. /**
  36506. * Creates a torus knot geometry
  36507. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36508. */
  36509. var TorusKnotGeometry = /** @class */ (function (_super) {
  36510. __extends(TorusKnotGeometry, _super);
  36511. /**
  36512. * Creates a torus knot geometry
  36513. * @param id defines the unique ID of the geometry
  36514. * @param scene defines the hosting scene
  36515. * @param radius defines the radius of the torus knot
  36516. * @param tube defines the thickness of the torus knot tube
  36517. * @param radialSegments defines the number of radial segments
  36518. * @param tubularSegments defines the number of tubular segments
  36519. * @param p defines the first number of windings
  36520. * @param q defines the second number of windings
  36521. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36522. * @param mesh defines the hosting mesh (can be null)
  36523. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36524. */
  36525. function TorusKnotGeometry(id, scene,
  36526. /**
  36527. * Defines the radius of the torus knot
  36528. */
  36529. radius,
  36530. /**
  36531. * Defines the thickness of the torus knot tube
  36532. */
  36533. tube,
  36534. /**
  36535. * Defines the number of radial segments
  36536. */
  36537. radialSegments,
  36538. /**
  36539. * Defines the number of tubular segments
  36540. */
  36541. tubularSegments,
  36542. /**
  36543. * Defines the first number of windings
  36544. */
  36545. p,
  36546. /**
  36547. * Defines the second number of windings
  36548. */
  36549. q, canBeRegenerated, mesh,
  36550. /**
  36551. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36552. */
  36553. side) {
  36554. if (mesh === void 0) { mesh = null; }
  36555. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36556. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36557. _this.radius = radius;
  36558. _this.tube = tube;
  36559. _this.radialSegments = radialSegments;
  36560. _this.tubularSegments = tubularSegments;
  36561. _this.p = p;
  36562. _this.q = q;
  36563. _this.side = side;
  36564. return _this;
  36565. }
  36566. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36567. 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 });
  36568. };
  36569. TorusKnotGeometry.prototype.copy = function (id) {
  36570. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36571. };
  36572. TorusKnotGeometry.prototype.serialize = function () {
  36573. var serializationObject = _super.prototype.serialize.call(this);
  36574. serializationObject.radius = this.radius;
  36575. serializationObject.tube = this.tube;
  36576. serializationObject.radialSegments = this.radialSegments;
  36577. serializationObject.tubularSegments = this.tubularSegments;
  36578. serializationObject.p = this.p;
  36579. serializationObject.q = this.q;
  36580. return serializationObject;
  36581. };
  36582. ;
  36583. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36584. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36585. return null; // null since geometry could be something else than a ground...
  36586. }
  36587. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36588. if (BABYLON.Tags) {
  36589. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36590. }
  36591. scene.pushGeometry(torusKnot, true);
  36592. return torusKnot;
  36593. };
  36594. return TorusKnotGeometry;
  36595. }(_PrimitiveGeometry));
  36596. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36597. //}
  36598. })(BABYLON || (BABYLON = {}));
  36599. //# sourceMappingURL=babylon.geometry.js.map
  36600. var BABYLON;
  36601. (function (BABYLON) {
  36602. /**
  36603. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36604. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36605. */
  36606. var PostProcessManager = /** @class */ (function () {
  36607. /**
  36608. * Creates a new instance of @see PostProcess
  36609. * @param scene The scene that the post process is associated with.
  36610. */
  36611. function PostProcessManager(scene) {
  36612. this._vertexBuffers = {};
  36613. this._scene = scene;
  36614. }
  36615. PostProcessManager.prototype._prepareBuffers = function () {
  36616. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36617. return;
  36618. }
  36619. // VBO
  36620. var vertices = [];
  36621. vertices.push(1, 1);
  36622. vertices.push(-1, 1);
  36623. vertices.push(-1, -1);
  36624. vertices.push(1, -1);
  36625. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36626. this._buildIndexBuffer();
  36627. };
  36628. PostProcessManager.prototype._buildIndexBuffer = function () {
  36629. // Indices
  36630. var indices = [];
  36631. indices.push(0);
  36632. indices.push(1);
  36633. indices.push(2);
  36634. indices.push(0);
  36635. indices.push(2);
  36636. indices.push(3);
  36637. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36638. };
  36639. /**
  36640. * Rebuilds the vertex buffers of the manager.
  36641. */
  36642. PostProcessManager.prototype._rebuild = function () {
  36643. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36644. if (!vb) {
  36645. return;
  36646. }
  36647. vb._rebuild();
  36648. this._buildIndexBuffer();
  36649. };
  36650. // Methods
  36651. /**
  36652. * Prepares a frame to be run through a post process.
  36653. * @param sourceTexture The input texture to the post procesess. (default: null)
  36654. * @param postProcesses An array of post processes to be run. (default: null)
  36655. * @returns True if the post processes were able to be run.
  36656. */
  36657. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36658. if (sourceTexture === void 0) { sourceTexture = null; }
  36659. if (postProcesses === void 0) { postProcesses = null; }
  36660. var camera = this._scene.activeCamera;
  36661. if (!camera) {
  36662. return false;
  36663. }
  36664. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  36665. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36666. return false;
  36667. }
  36668. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36669. return true;
  36670. };
  36671. /**
  36672. * Manually render a set of post processes to a texture.
  36673. * @param postProcesses An array of post processes to be run.
  36674. * @param targetTexture The target texture to render to.
  36675. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36676. */
  36677. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36678. if (targetTexture === void 0) { targetTexture = null; }
  36679. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36680. var engine = this._scene.getEngine();
  36681. for (var index = 0; index < postProcesses.length; index++) {
  36682. if (index < postProcesses.length - 1) {
  36683. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36684. }
  36685. else {
  36686. if (targetTexture) {
  36687. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36688. }
  36689. else {
  36690. engine.restoreDefaultFramebuffer();
  36691. }
  36692. }
  36693. var pp = postProcesses[index];
  36694. var effect = pp.apply();
  36695. if (effect) {
  36696. pp.onBeforeRenderObservable.notifyObservers(effect);
  36697. // VBOs
  36698. this._prepareBuffers();
  36699. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36700. // Draw order
  36701. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36702. pp.onAfterRenderObservable.notifyObservers(effect);
  36703. }
  36704. }
  36705. // Restore depth buffer
  36706. engine.setDepthBuffer(true);
  36707. engine.setDepthWrite(true);
  36708. };
  36709. /**
  36710. * Finalize the result of the output of the postprocesses.
  36711. * @param doNotPresent If true the result will not be displayed to the screen.
  36712. * @param targetTexture The target texture to render to.
  36713. * @param faceIndex The index of the face to bind the target texture to.
  36714. * @param postProcesses The array of post processes to render.
  36715. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36716. */
  36717. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36718. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36719. var camera = this._scene.activeCamera;
  36720. if (!camera) {
  36721. return;
  36722. }
  36723. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  36724. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36725. return;
  36726. }
  36727. var engine = this._scene.getEngine();
  36728. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36729. if (index < len - 1) {
  36730. postProcesses[index + 1].activate(camera, targetTexture);
  36731. }
  36732. else {
  36733. if (targetTexture) {
  36734. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36735. }
  36736. else {
  36737. engine.restoreDefaultFramebuffer();
  36738. }
  36739. }
  36740. if (doNotPresent) {
  36741. break;
  36742. }
  36743. var pp = postProcesses[index];
  36744. var effect = pp.apply();
  36745. if (effect) {
  36746. pp.onBeforeRenderObservable.notifyObservers(effect);
  36747. // VBOs
  36748. this._prepareBuffers();
  36749. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36750. // Draw order
  36751. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36752. pp.onAfterRenderObservable.notifyObservers(effect);
  36753. }
  36754. }
  36755. // Restore states
  36756. engine.setDepthBuffer(true);
  36757. engine.setDepthWrite(true);
  36758. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36759. };
  36760. /**
  36761. * Disposes of the post process manager.
  36762. */
  36763. PostProcessManager.prototype.dispose = function () {
  36764. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36765. if (buffer) {
  36766. buffer.dispose();
  36767. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36768. }
  36769. if (this._indexBuffer) {
  36770. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36771. this._indexBuffer = null;
  36772. }
  36773. };
  36774. return PostProcessManager;
  36775. }());
  36776. BABYLON.PostProcessManager = PostProcessManager;
  36777. })(BABYLON || (BABYLON = {}));
  36778. //# sourceMappingURL=babylon.postProcessManager.js.map
  36779. var BABYLON;
  36780. (function (BABYLON) {
  36781. /**
  36782. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36783. */
  36784. var PerformanceMonitor = /** @class */ (function () {
  36785. /**
  36786. * constructor
  36787. * @param frameSampleSize The number of samples required to saturate the sliding window
  36788. */
  36789. function PerformanceMonitor(frameSampleSize) {
  36790. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36791. this._enabled = true;
  36792. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36793. }
  36794. /**
  36795. * Samples current frame
  36796. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36797. */
  36798. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36799. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36800. if (!this._enabled)
  36801. return;
  36802. if (this._lastFrameTimeMs != null) {
  36803. var dt = timeMs - this._lastFrameTimeMs;
  36804. this._rollingFrameTime.add(dt);
  36805. }
  36806. this._lastFrameTimeMs = timeMs;
  36807. };
  36808. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36809. /**
  36810. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36811. * @return Average frame time in milliseconds
  36812. */
  36813. get: function () {
  36814. return this._rollingFrameTime.average;
  36815. },
  36816. enumerable: true,
  36817. configurable: true
  36818. });
  36819. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36820. /**
  36821. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36822. * @return Frame time variance in milliseconds squared
  36823. */
  36824. get: function () {
  36825. return this._rollingFrameTime.variance;
  36826. },
  36827. enumerable: true,
  36828. configurable: true
  36829. });
  36830. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36831. /**
  36832. * Returns the frame time of the most recent frame
  36833. * @return Frame time in milliseconds
  36834. */
  36835. get: function () {
  36836. return this._rollingFrameTime.history(0);
  36837. },
  36838. enumerable: true,
  36839. configurable: true
  36840. });
  36841. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36842. /**
  36843. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36844. * @return Framerate in frames per second
  36845. */
  36846. get: function () {
  36847. return 1000.0 / this._rollingFrameTime.average;
  36848. },
  36849. enumerable: true,
  36850. configurable: true
  36851. });
  36852. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36853. /**
  36854. * Returns the average framerate in frames per second using the most recent frame time
  36855. * @return Framerate in frames per second
  36856. */
  36857. get: function () {
  36858. var history = this._rollingFrameTime.history(0);
  36859. if (history === 0) {
  36860. return 0;
  36861. }
  36862. return 1000.0 / history;
  36863. },
  36864. enumerable: true,
  36865. configurable: true
  36866. });
  36867. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36868. /**
  36869. * Returns true if enough samples have been taken to completely fill the sliding window
  36870. * @return true if saturated
  36871. */
  36872. get: function () {
  36873. return this._rollingFrameTime.isSaturated();
  36874. },
  36875. enumerable: true,
  36876. configurable: true
  36877. });
  36878. /**
  36879. * Enables contributions to the sliding window sample set
  36880. */
  36881. PerformanceMonitor.prototype.enable = function () {
  36882. this._enabled = true;
  36883. };
  36884. /**
  36885. * Disables contributions to the sliding window sample set
  36886. * Samples will not be interpolated over the disabled period
  36887. */
  36888. PerformanceMonitor.prototype.disable = function () {
  36889. this._enabled = false;
  36890. //clear last sample to avoid interpolating over the disabled period when next enabled
  36891. this._lastFrameTimeMs = null;
  36892. };
  36893. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36894. /**
  36895. * Returns true if sampling is enabled
  36896. * @return true if enabled
  36897. */
  36898. get: function () {
  36899. return this._enabled;
  36900. },
  36901. enumerable: true,
  36902. configurable: true
  36903. });
  36904. /**
  36905. * Resets performance monitor
  36906. */
  36907. PerformanceMonitor.prototype.reset = function () {
  36908. //clear last sample to avoid interpolating over the disabled period when next enabled
  36909. this._lastFrameTimeMs = null;
  36910. //wipe record
  36911. this._rollingFrameTime.reset();
  36912. };
  36913. return PerformanceMonitor;
  36914. }());
  36915. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36916. /**
  36917. * RollingAverage
  36918. *
  36919. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36920. */
  36921. var RollingAverage = /** @class */ (function () {
  36922. /**
  36923. * constructor
  36924. * @param length The number of samples required to saturate the sliding window
  36925. */
  36926. function RollingAverage(length) {
  36927. this._samples = new Array(length);
  36928. this.reset();
  36929. }
  36930. /**
  36931. * Adds a sample to the sample set
  36932. * @param v The sample value
  36933. */
  36934. RollingAverage.prototype.add = function (v) {
  36935. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36936. var delta;
  36937. //we need to check if we've already wrapped round
  36938. if (this.isSaturated()) {
  36939. //remove bottom of stack from mean
  36940. var bottomValue = this._samples[this._pos];
  36941. delta = bottomValue - this.average;
  36942. this.average -= delta / (this._sampleCount - 1);
  36943. this._m2 -= delta * (bottomValue - this.average);
  36944. }
  36945. else {
  36946. this._sampleCount++;
  36947. }
  36948. //add new value to mean
  36949. delta = v - this.average;
  36950. this.average += delta / (this._sampleCount);
  36951. this._m2 += delta * (v - this.average);
  36952. //set the new variance
  36953. this.variance = this._m2 / (this._sampleCount - 1);
  36954. this._samples[this._pos] = v;
  36955. this._pos++;
  36956. this._pos %= this._samples.length; //positive wrap around
  36957. };
  36958. /**
  36959. * Returns previously added values or null if outside of history or outside the sliding window domain
  36960. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36961. * @return Value previously recorded with add() or null if outside of range
  36962. */
  36963. RollingAverage.prototype.history = function (i) {
  36964. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36965. return 0;
  36966. }
  36967. var i0 = this._wrapPosition(this._pos - 1.0);
  36968. return this._samples[this._wrapPosition(i0 - i)];
  36969. };
  36970. /**
  36971. * Returns true if enough samples have been taken to completely fill the sliding window
  36972. * @return true if sample-set saturated
  36973. */
  36974. RollingAverage.prototype.isSaturated = function () {
  36975. return this._sampleCount >= this._samples.length;
  36976. };
  36977. /**
  36978. * Resets the rolling average (equivalent to 0 samples taken so far)
  36979. */
  36980. RollingAverage.prototype.reset = function () {
  36981. this.average = 0;
  36982. this.variance = 0;
  36983. this._sampleCount = 0;
  36984. this._pos = 0;
  36985. this._m2 = 0;
  36986. };
  36987. /**
  36988. * Wraps a value around the sample range boundaries
  36989. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36990. * @return Wrapped position in sample range
  36991. */
  36992. RollingAverage.prototype._wrapPosition = function (i) {
  36993. var max = this._samples.length;
  36994. return ((i % max) + max) % max;
  36995. };
  36996. return RollingAverage;
  36997. }());
  36998. BABYLON.RollingAverage = RollingAverage;
  36999. })(BABYLON || (BABYLON = {}));
  37000. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37001. var BABYLON;
  37002. (function (BABYLON) {
  37003. /**
  37004. * This groups together the common properties used for image processing either in direct forward pass
  37005. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37006. * or not.
  37007. */
  37008. var ImageProcessingConfiguration = /** @class */ (function () {
  37009. function ImageProcessingConfiguration() {
  37010. /**
  37011. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37012. */
  37013. this.colorCurves = new BABYLON.ColorCurves();
  37014. this._colorCurvesEnabled = false;
  37015. this._colorGradingEnabled = false;
  37016. this._colorGradingWithGreenDepth = true;
  37017. this._colorGradingBGR = true;
  37018. this._exposure = 1.0;
  37019. this._toneMappingEnabled = false;
  37020. this._contrast = 1.0;
  37021. /**
  37022. * Vignette stretch size.
  37023. */
  37024. this.vignetteStretch = 0;
  37025. /**
  37026. * Vignette centre X Offset.
  37027. */
  37028. this.vignetteCentreX = 0;
  37029. /**
  37030. * Vignette centre Y Offset.
  37031. */
  37032. this.vignetteCentreY = 0;
  37033. /**
  37034. * Vignette weight or intensity of the vignette effect.
  37035. */
  37036. this.vignetteWeight = 1.5;
  37037. /**
  37038. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37039. * if vignetteEnabled is set to true.
  37040. */
  37041. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37042. /**
  37043. * Camera field of view used by the Vignette effect.
  37044. */
  37045. this.vignetteCameraFov = 0.5;
  37046. this._grainEnabled = false;
  37047. this._grainIntensity = 30;
  37048. this._grainAnimated = false;
  37049. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37050. this._vignetteEnabled = false;
  37051. this._applyByPostProcess = false;
  37052. this._isEnabled = true;
  37053. /**
  37054. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37055. * @type {BABYLON.Observable}
  37056. */
  37057. this.onUpdateParameters = new BABYLON.Observable();
  37058. }
  37059. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37060. /**
  37061. * Gets wether the color curves effect is enabled.
  37062. */
  37063. get: function () {
  37064. return this._colorCurvesEnabled;
  37065. },
  37066. /**
  37067. * Sets wether the color curves effect is enabled.
  37068. */
  37069. set: function (value) {
  37070. if (this._colorCurvesEnabled === value) {
  37071. return;
  37072. }
  37073. this._colorCurvesEnabled = value;
  37074. this._updateParameters();
  37075. },
  37076. enumerable: true,
  37077. configurable: true
  37078. });
  37079. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37080. /**
  37081. * Gets wether the color grading effect is enabled.
  37082. */
  37083. get: function () {
  37084. return this._colorGradingEnabled;
  37085. },
  37086. /**
  37087. * Sets wether the color grading effect is enabled.
  37088. */
  37089. set: function (value) {
  37090. if (this._colorGradingEnabled === value) {
  37091. return;
  37092. }
  37093. this._colorGradingEnabled = value;
  37094. this._updateParameters();
  37095. },
  37096. enumerable: true,
  37097. configurable: true
  37098. });
  37099. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37100. /**
  37101. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37102. */
  37103. get: function () {
  37104. return this._colorGradingWithGreenDepth;
  37105. },
  37106. /**
  37107. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37108. */
  37109. set: function (value) {
  37110. if (this._colorGradingWithGreenDepth === value) {
  37111. return;
  37112. }
  37113. this._colorGradingWithGreenDepth = value;
  37114. this._updateParameters();
  37115. },
  37116. enumerable: true,
  37117. configurable: true
  37118. });
  37119. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37120. /**
  37121. * Gets wether the color grading texture contains BGR values.
  37122. */
  37123. get: function () {
  37124. return this._colorGradingBGR;
  37125. },
  37126. /**
  37127. * Sets wether the color grading texture contains BGR values.
  37128. */
  37129. set: function (value) {
  37130. if (this._colorGradingBGR === value) {
  37131. return;
  37132. }
  37133. this._colorGradingBGR = value;
  37134. this._updateParameters();
  37135. },
  37136. enumerable: true,
  37137. configurable: true
  37138. });
  37139. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37140. /**
  37141. * Gets the Exposure used in the effect.
  37142. */
  37143. get: function () {
  37144. return this._exposure;
  37145. },
  37146. /**
  37147. * Sets the Exposure used in the effect.
  37148. */
  37149. set: function (value) {
  37150. if (this._exposure === value) {
  37151. return;
  37152. }
  37153. this._exposure = value;
  37154. this._updateParameters();
  37155. },
  37156. enumerable: true,
  37157. configurable: true
  37158. });
  37159. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37160. /**
  37161. * Gets wether the tone mapping effect is enabled.
  37162. */
  37163. get: function () {
  37164. return this._toneMappingEnabled;
  37165. },
  37166. /**
  37167. * Sets wether the tone mapping effect is enabled.
  37168. */
  37169. set: function (value) {
  37170. if (this._toneMappingEnabled === value) {
  37171. return;
  37172. }
  37173. this._toneMappingEnabled = value;
  37174. this._updateParameters();
  37175. },
  37176. enumerable: true,
  37177. configurable: true
  37178. });
  37179. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37180. /**
  37181. * Gets the contrast used in the effect.
  37182. */
  37183. get: function () {
  37184. return this._contrast;
  37185. },
  37186. /**
  37187. * Sets the contrast used in the effect.
  37188. */
  37189. set: function (value) {
  37190. if (this._contrast === value) {
  37191. return;
  37192. }
  37193. this._contrast = value;
  37194. this._updateParameters();
  37195. },
  37196. enumerable: true,
  37197. configurable: true
  37198. });
  37199. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37200. /**
  37201. * If the grain effect should be enabled.
  37202. */
  37203. get: function () {
  37204. return this._grainEnabled;
  37205. },
  37206. set: function (value) {
  37207. if (this._grainEnabled === value) {
  37208. return;
  37209. }
  37210. this._grainEnabled = value;
  37211. this._updateParameters();
  37212. },
  37213. enumerable: true,
  37214. configurable: true
  37215. });
  37216. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37217. /**
  37218. * Amount of grain to be applied by the grain effect.
  37219. */
  37220. get: function () {
  37221. return this._grainIntensity;
  37222. },
  37223. set: function (value) {
  37224. if (this._grainIntensity === value) {
  37225. return;
  37226. }
  37227. this._grainIntensity = value;
  37228. },
  37229. enumerable: true,
  37230. configurable: true
  37231. });
  37232. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37233. /**
  37234. * If the grain effect should be animated.
  37235. */
  37236. get: function () {
  37237. return this._grainAnimated;
  37238. },
  37239. set: function (value) {
  37240. if (this._grainAnimated === value) {
  37241. return;
  37242. }
  37243. this._grainAnimated = value;
  37244. this._updateParameters();
  37245. },
  37246. enumerable: true,
  37247. configurable: true
  37248. });
  37249. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37250. /**
  37251. * Gets the vignette blend mode allowing different kind of effect.
  37252. */
  37253. get: function () {
  37254. return this._vignetteBlendMode;
  37255. },
  37256. /**
  37257. * Sets the vignette blend mode allowing different kind of effect.
  37258. */
  37259. set: function (value) {
  37260. if (this._vignetteBlendMode === value) {
  37261. return;
  37262. }
  37263. this._vignetteBlendMode = value;
  37264. this._updateParameters();
  37265. },
  37266. enumerable: true,
  37267. configurable: true
  37268. });
  37269. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37270. /**
  37271. * Gets wether the vignette effect is enabled.
  37272. */
  37273. get: function () {
  37274. return this._vignetteEnabled;
  37275. },
  37276. /**
  37277. * Sets wether the vignette effect is enabled.
  37278. */
  37279. set: function (value) {
  37280. if (this._vignetteEnabled === value) {
  37281. return;
  37282. }
  37283. this._vignetteEnabled = value;
  37284. this._updateParameters();
  37285. },
  37286. enumerable: true,
  37287. configurable: true
  37288. });
  37289. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37290. /**
  37291. * Gets wether the image processing is applied through a post process or not.
  37292. */
  37293. get: function () {
  37294. return this._applyByPostProcess;
  37295. },
  37296. /**
  37297. * Sets wether the image processing is applied through a post process or not.
  37298. */
  37299. set: function (value) {
  37300. if (this._applyByPostProcess === value) {
  37301. return;
  37302. }
  37303. this._applyByPostProcess = value;
  37304. this._updateParameters();
  37305. },
  37306. enumerable: true,
  37307. configurable: true
  37308. });
  37309. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37310. /**
  37311. * Gets wether the image processing is enabled or not.
  37312. */
  37313. get: function () {
  37314. return this._isEnabled;
  37315. },
  37316. /**
  37317. * Sets wether the image processing is enabled or not.
  37318. */
  37319. set: function (value) {
  37320. if (this._isEnabled === value) {
  37321. return;
  37322. }
  37323. this._isEnabled = value;
  37324. this._updateParameters();
  37325. },
  37326. enumerable: true,
  37327. configurable: true
  37328. });
  37329. /**
  37330. * Method called each time the image processing information changes requires to recompile the effect.
  37331. */
  37332. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37333. this.onUpdateParameters.notifyObservers(this);
  37334. };
  37335. ImageProcessingConfiguration.prototype.getClassName = function () {
  37336. return "ImageProcessingConfiguration";
  37337. };
  37338. /**
  37339. * Prepare the list of uniforms associated with the Image Processing effects.
  37340. * @param uniformsList The list of uniforms used in the effect
  37341. * @param defines the list of defines currently in use
  37342. */
  37343. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37344. if (defines.EXPOSURE) {
  37345. uniforms.push("exposureLinear");
  37346. }
  37347. if (defines.CONTRAST) {
  37348. uniforms.push("contrast");
  37349. }
  37350. if (defines.COLORGRADING) {
  37351. uniforms.push("colorTransformSettings");
  37352. }
  37353. if (defines.VIGNETTE) {
  37354. uniforms.push("vInverseScreenSize");
  37355. uniforms.push("vignetteSettings1");
  37356. uniforms.push("vignetteSettings2");
  37357. }
  37358. if (defines.COLORCURVES) {
  37359. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37360. }
  37361. if (defines.GRAIN) {
  37362. uniforms.push("grainVarianceAmount");
  37363. uniforms.push("grainAnimatedSeed");
  37364. }
  37365. };
  37366. /**
  37367. * Prepare the list of samplers associated with the Image Processing effects.
  37368. * @param uniformsList The list of uniforms used in the effect
  37369. * @param defines the list of defines currently in use
  37370. */
  37371. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37372. if (defines.COLORGRADING) {
  37373. samplersList.push("txColorTransform");
  37374. }
  37375. };
  37376. /**
  37377. * Prepare the list of defines associated to the shader.
  37378. * @param defines the list of defines to complete
  37379. */
  37380. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37381. if (forPostProcess === void 0) { forPostProcess = false; }
  37382. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37383. defines.VIGNETTE = false;
  37384. defines.TONEMAPPING = false;
  37385. defines.CONTRAST = false;
  37386. defines.EXPOSURE = false;
  37387. defines.COLORCURVES = false;
  37388. defines.COLORGRADING = false;
  37389. defines.COLORGRADING3D = false;
  37390. defines.IMAGEPROCESSING = false;
  37391. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37392. return;
  37393. }
  37394. defines.VIGNETTE = this.vignetteEnabled;
  37395. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37396. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37397. defines.TONEMAPPING = this.toneMappingEnabled;
  37398. defines.CONTRAST = (this.contrast !== 1.0);
  37399. defines.EXPOSURE = (this.exposure !== 1.0);
  37400. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37401. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37402. if (defines.COLORGRADING) {
  37403. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37404. }
  37405. else {
  37406. defines.COLORGRADING3D = false;
  37407. }
  37408. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37409. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37410. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37411. defines.GRAIN = this.grainEnabled;
  37412. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37413. };
  37414. /**
  37415. * Returns true if all the image processing information are ready.
  37416. */
  37417. ImageProcessingConfiguration.prototype.isReady = function () {
  37418. // Color Grading texure can not be none blocking.
  37419. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37420. };
  37421. /**
  37422. * Binds the image processing to the shader.
  37423. * @param effect The effect to bind to
  37424. */
  37425. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37426. if (aspectRatio === void 0) { aspectRatio = 1; }
  37427. // Color Curves
  37428. if (this._colorCurvesEnabled && this.colorCurves) {
  37429. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37430. }
  37431. // Vignette
  37432. if (this._vignetteEnabled) {
  37433. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37434. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37435. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37436. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37437. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37438. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37439. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37440. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37441. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37442. var vignettePower = -2.0 * this.vignetteWeight;
  37443. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37444. }
  37445. // Exposure
  37446. effect.setFloat("exposureLinear", this.exposure);
  37447. // Contrast
  37448. effect.setFloat("contrast", this.contrast);
  37449. // Color transform settings
  37450. if (this.colorGradingTexture) {
  37451. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37452. var textureSize = this.colorGradingTexture.getSize().height;
  37453. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37454. 0.5 / textureSize, // textureOffset
  37455. textureSize, // textureSize
  37456. this.colorGradingTexture.level // weight
  37457. );
  37458. }
  37459. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37460. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37461. };
  37462. /**
  37463. * Clones the current image processing instance.
  37464. * @return The cloned image processing
  37465. */
  37466. ImageProcessingConfiguration.prototype.clone = function () {
  37467. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37468. };
  37469. /**
  37470. * Serializes the current image processing instance to a json representation.
  37471. * @return a JSON representation
  37472. */
  37473. ImageProcessingConfiguration.prototype.serialize = function () {
  37474. return BABYLON.SerializationHelper.Serialize(this);
  37475. };
  37476. /**
  37477. * Parses the image processing from a json representation.
  37478. * @param source the JSON source to parse
  37479. * @return The parsed image processing
  37480. */
  37481. ImageProcessingConfiguration.Parse = function (source) {
  37482. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37483. };
  37484. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37485. /**
  37486. * Used to apply the vignette as a mix with the pixel color.
  37487. */
  37488. get: function () {
  37489. return this._VIGNETTEMODE_MULTIPLY;
  37490. },
  37491. enumerable: true,
  37492. configurable: true
  37493. });
  37494. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37495. /**
  37496. * Used to apply the vignette as a replacement of the pixel color.
  37497. */
  37498. get: function () {
  37499. return this._VIGNETTEMODE_OPAQUE;
  37500. },
  37501. enumerable: true,
  37502. configurable: true
  37503. });
  37504. // Static constants associated to the image processing.
  37505. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37506. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37507. __decorate([
  37508. BABYLON.serializeAsColorCurves()
  37509. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37510. __decorate([
  37511. BABYLON.serialize()
  37512. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37513. __decorate([
  37514. BABYLON.serializeAsTexture()
  37515. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37516. __decorate([
  37517. BABYLON.serialize()
  37518. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37519. __decorate([
  37520. BABYLON.serialize()
  37521. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37522. __decorate([
  37523. BABYLON.serialize()
  37524. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37525. __decorate([
  37526. BABYLON.serialize()
  37527. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37528. __decorate([
  37529. BABYLON.serialize()
  37530. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37531. __decorate([
  37532. BABYLON.serialize()
  37533. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37534. __decorate([
  37535. BABYLON.serialize()
  37536. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37537. __decorate([
  37538. BABYLON.serialize()
  37539. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37540. __decorate([
  37541. BABYLON.serialize()
  37542. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37543. __decorate([
  37544. BABYLON.serialize()
  37545. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37546. __decorate([
  37547. BABYLON.serializeAsColor4()
  37548. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37549. __decorate([
  37550. BABYLON.serialize()
  37551. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37552. __decorate([
  37553. BABYLON.serialize()
  37554. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37555. __decorate([
  37556. BABYLON.serialize()
  37557. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37558. __decorate([
  37559. BABYLON.serialize()
  37560. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37561. __decorate([
  37562. BABYLON.serialize()
  37563. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37564. __decorate([
  37565. BABYLON.serialize()
  37566. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37567. __decorate([
  37568. BABYLON.serialize()
  37569. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37570. __decorate([
  37571. BABYLON.serialize()
  37572. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37573. return ImageProcessingConfiguration;
  37574. }());
  37575. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37576. })(BABYLON || (BABYLON = {}));
  37577. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37578. var BABYLON;
  37579. (function (BABYLON) {
  37580. /**
  37581. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37582. * It can help converting any input color in a desired output one. This can then be used to create effects
  37583. * from sepia, black and white to sixties or futuristic rendering...
  37584. *
  37585. * The only supported format is currently 3dl.
  37586. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37587. */
  37588. var ColorGradingTexture = /** @class */ (function (_super) {
  37589. __extends(ColorGradingTexture, _super);
  37590. /**
  37591. * Instantiates a ColorGradingTexture from the following parameters.
  37592. *
  37593. * @param url The location of the color gradind data (currently only supporting 3dl)
  37594. * @param scene The scene the texture will be used in
  37595. */
  37596. function ColorGradingTexture(url, scene) {
  37597. var _this = _super.call(this, scene) || this;
  37598. if (!url) {
  37599. return _this;
  37600. }
  37601. _this._engine = scene.getEngine();
  37602. _this._textureMatrix = BABYLON.Matrix.Identity();
  37603. _this.name = url;
  37604. _this.url = url;
  37605. _this.hasAlpha = false;
  37606. _this.isCube = false;
  37607. _this.is3D = _this._engine.webGLVersion > 1;
  37608. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37609. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37610. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37611. _this.anisotropicFilteringLevel = 1;
  37612. _this._texture = _this._getFromCache(url, true);
  37613. if (!_this._texture) {
  37614. if (!scene.useDelayedTextureLoading) {
  37615. _this.loadTexture();
  37616. }
  37617. else {
  37618. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37619. }
  37620. }
  37621. return _this;
  37622. }
  37623. /**
  37624. * Returns the texture matrix used in most of the material.
  37625. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37626. */
  37627. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37628. return this._textureMatrix;
  37629. };
  37630. /**
  37631. * Occurs when the file being loaded is a .3dl LUT file.
  37632. */
  37633. ColorGradingTexture.prototype.load3dlTexture = function () {
  37634. var engine = this._engine;
  37635. var texture;
  37636. if (engine.webGLVersion === 1) {
  37637. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37638. }
  37639. else {
  37640. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37641. }
  37642. this._texture = texture;
  37643. var callback = function (text) {
  37644. if (typeof text !== "string") {
  37645. return;
  37646. }
  37647. var data = null;
  37648. var tempData = null;
  37649. var line;
  37650. var lines = text.split('\n');
  37651. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37652. var maxColor = 0;
  37653. for (var i = 0; i < lines.length; i++) {
  37654. line = lines[i];
  37655. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37656. continue;
  37657. if (line.indexOf('#') === 0)
  37658. continue;
  37659. var words = line.split(" ");
  37660. if (size === 0) {
  37661. // Number of space + one
  37662. size = words.length;
  37663. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37664. tempData = new Float32Array(size * size * size * 4);
  37665. continue;
  37666. }
  37667. if (size != 0) {
  37668. var r = Math.max(parseInt(words[0]), 0);
  37669. var g = Math.max(parseInt(words[1]), 0);
  37670. var b = Math.max(parseInt(words[2]), 0);
  37671. maxColor = Math.max(r, maxColor);
  37672. maxColor = Math.max(g, maxColor);
  37673. maxColor = Math.max(b, maxColor);
  37674. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37675. if (tempData) {
  37676. tempData[pixelStorageIndex + 0] = r;
  37677. tempData[pixelStorageIndex + 1] = g;
  37678. tempData[pixelStorageIndex + 2] = b;
  37679. }
  37680. pixelIndexSlice++;
  37681. if (pixelIndexSlice % size == 0) {
  37682. pixelIndexH++;
  37683. pixelIndexSlice = 0;
  37684. if (pixelIndexH % size == 0) {
  37685. pixelIndexW++;
  37686. pixelIndexH = 0;
  37687. }
  37688. }
  37689. }
  37690. }
  37691. if (tempData && data) {
  37692. for (var i = 0; i < tempData.length; i++) {
  37693. if (i > 0 && (i + 1) % 4 === 0) {
  37694. data[i] = 255;
  37695. }
  37696. else {
  37697. var value = tempData[i];
  37698. data[i] = (value / maxColor * 255);
  37699. }
  37700. }
  37701. }
  37702. if (texture.is3D) {
  37703. texture.updateSize(size, size, size);
  37704. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37705. }
  37706. else {
  37707. texture.updateSize(size * size, size);
  37708. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37709. }
  37710. };
  37711. var scene = this.getScene();
  37712. if (scene) {
  37713. scene._loadFile(this.url, callback);
  37714. }
  37715. else {
  37716. this._engine._loadFile(this.url, callback);
  37717. }
  37718. return this._texture;
  37719. };
  37720. /**
  37721. * Starts the loading process of the texture.
  37722. */
  37723. ColorGradingTexture.prototype.loadTexture = function () {
  37724. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37725. this.load3dlTexture();
  37726. }
  37727. };
  37728. /**
  37729. * Clones the color gradind texture.
  37730. */
  37731. ColorGradingTexture.prototype.clone = function () {
  37732. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37733. // Base texture
  37734. newTexture.level = this.level;
  37735. return newTexture;
  37736. };
  37737. /**
  37738. * Called during delayed load for textures.
  37739. */
  37740. ColorGradingTexture.prototype.delayLoad = function () {
  37741. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37742. return;
  37743. }
  37744. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37745. this._texture = this._getFromCache(this.url, true);
  37746. if (!this._texture) {
  37747. this.loadTexture();
  37748. }
  37749. };
  37750. /**
  37751. * Parses a color grading texture serialized by Babylon.
  37752. * @param parsedTexture The texture information being parsedTexture
  37753. * @param scene The scene to load the texture in
  37754. * @param rootUrl The root url of the data assets to load
  37755. * @return A color gradind texture
  37756. */
  37757. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37758. var texture = null;
  37759. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37760. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37761. texture.name = parsedTexture.name;
  37762. texture.level = parsedTexture.level;
  37763. }
  37764. return texture;
  37765. };
  37766. /**
  37767. * Serializes the LUT texture to json format.
  37768. */
  37769. ColorGradingTexture.prototype.serialize = function () {
  37770. if (!this.name) {
  37771. return null;
  37772. }
  37773. var serializationObject = {};
  37774. serializationObject.name = this.name;
  37775. serializationObject.level = this.level;
  37776. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37777. return serializationObject;
  37778. };
  37779. /**
  37780. * Empty line regex stored for GC.
  37781. */
  37782. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37783. return ColorGradingTexture;
  37784. }(BABYLON.BaseTexture));
  37785. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37786. })(BABYLON || (BABYLON = {}));
  37787. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37788. var BABYLON;
  37789. (function (BABYLON) {
  37790. /**
  37791. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37792. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37793. * 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;
  37794. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37795. */
  37796. var ColorCurves = /** @class */ (function () {
  37797. function ColorCurves() {
  37798. this._dirty = true;
  37799. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37800. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37801. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37802. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37803. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37804. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37805. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37806. this._globalHue = 30;
  37807. this._globalDensity = 0;
  37808. this._globalSaturation = 0;
  37809. this._globalExposure = 0;
  37810. this._highlightsHue = 30;
  37811. this._highlightsDensity = 0;
  37812. this._highlightsSaturation = 0;
  37813. this._highlightsExposure = 0;
  37814. this._midtonesHue = 30;
  37815. this._midtonesDensity = 0;
  37816. this._midtonesSaturation = 0;
  37817. this._midtonesExposure = 0;
  37818. this._shadowsHue = 30;
  37819. this._shadowsDensity = 0;
  37820. this._shadowsSaturation = 0;
  37821. this._shadowsExposure = 0;
  37822. }
  37823. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37824. /**
  37825. * Gets the global Hue value.
  37826. * 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).
  37827. */
  37828. get: function () {
  37829. return this._globalHue;
  37830. },
  37831. /**
  37832. * Sets the global Hue value.
  37833. * 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).
  37834. */
  37835. set: function (value) {
  37836. this._globalHue = value;
  37837. this._dirty = true;
  37838. },
  37839. enumerable: true,
  37840. configurable: true
  37841. });
  37842. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37843. /**
  37844. * Gets the global Density value.
  37845. * 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.
  37846. * Values less than zero provide a filter of opposite hue.
  37847. */
  37848. get: function () {
  37849. return this._globalDensity;
  37850. },
  37851. /**
  37852. * Sets the global Density value.
  37853. * 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.
  37854. * Values less than zero provide a filter of opposite hue.
  37855. */
  37856. set: function (value) {
  37857. this._globalDensity = value;
  37858. this._dirty = true;
  37859. },
  37860. enumerable: true,
  37861. configurable: true
  37862. });
  37863. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37864. /**
  37865. * Gets the global Saturation value.
  37866. * 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.
  37867. */
  37868. get: function () {
  37869. return this._globalSaturation;
  37870. },
  37871. /**
  37872. * Sets the global Saturation value.
  37873. * 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.
  37874. */
  37875. set: function (value) {
  37876. this._globalSaturation = value;
  37877. this._dirty = true;
  37878. },
  37879. enumerable: true,
  37880. configurable: true
  37881. });
  37882. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37883. /**
  37884. * Gets the highlights Hue value.
  37885. * 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).
  37886. */
  37887. get: function () {
  37888. return this._highlightsHue;
  37889. },
  37890. /**
  37891. * Sets the highlights Hue value.
  37892. * 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).
  37893. */
  37894. set: function (value) {
  37895. this._highlightsHue = value;
  37896. this._dirty = true;
  37897. },
  37898. enumerable: true,
  37899. configurable: true
  37900. });
  37901. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37902. /**
  37903. * Gets the highlights Density value.
  37904. * 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.
  37905. * Values less than zero provide a filter of opposite hue.
  37906. */
  37907. get: function () {
  37908. return this._highlightsDensity;
  37909. },
  37910. /**
  37911. * Sets the highlights Density value.
  37912. * 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.
  37913. * Values less than zero provide a filter of opposite hue.
  37914. */
  37915. set: function (value) {
  37916. this._highlightsDensity = value;
  37917. this._dirty = true;
  37918. },
  37919. enumerable: true,
  37920. configurable: true
  37921. });
  37922. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37923. /**
  37924. * Gets the highlights Saturation value.
  37925. * 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.
  37926. */
  37927. get: function () {
  37928. return this._highlightsSaturation;
  37929. },
  37930. /**
  37931. * Sets the highlights Saturation value.
  37932. * 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.
  37933. */
  37934. set: function (value) {
  37935. this._highlightsSaturation = value;
  37936. this._dirty = true;
  37937. },
  37938. enumerable: true,
  37939. configurable: true
  37940. });
  37941. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37942. /**
  37943. * Gets the highlights Exposure value.
  37944. * 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.
  37945. */
  37946. get: function () {
  37947. return this._highlightsExposure;
  37948. },
  37949. /**
  37950. * Sets the highlights Exposure value.
  37951. * 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.
  37952. */
  37953. set: function (value) {
  37954. this._highlightsExposure = value;
  37955. this._dirty = true;
  37956. },
  37957. enumerable: true,
  37958. configurable: true
  37959. });
  37960. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37961. /**
  37962. * Gets the midtones Hue value.
  37963. * 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).
  37964. */
  37965. get: function () {
  37966. return this._midtonesHue;
  37967. },
  37968. /**
  37969. * Sets the midtones Hue value.
  37970. * 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).
  37971. */
  37972. set: function (value) {
  37973. this._midtonesHue = value;
  37974. this._dirty = true;
  37975. },
  37976. enumerable: true,
  37977. configurable: true
  37978. });
  37979. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37980. /**
  37981. * Gets the midtones Density value.
  37982. * 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.
  37983. * Values less than zero provide a filter of opposite hue.
  37984. */
  37985. get: function () {
  37986. return this._midtonesDensity;
  37987. },
  37988. /**
  37989. * Sets the midtones Density value.
  37990. * 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.
  37991. * Values less than zero provide a filter of opposite hue.
  37992. */
  37993. set: function (value) {
  37994. this._midtonesDensity = value;
  37995. this._dirty = true;
  37996. },
  37997. enumerable: true,
  37998. configurable: true
  37999. });
  38000. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38001. /**
  38002. * Gets the midtones Saturation value.
  38003. * 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.
  38004. */
  38005. get: function () {
  38006. return this._midtonesSaturation;
  38007. },
  38008. /**
  38009. * Sets the midtones Saturation value.
  38010. * 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.
  38011. */
  38012. set: function (value) {
  38013. this._midtonesSaturation = value;
  38014. this._dirty = true;
  38015. },
  38016. enumerable: true,
  38017. configurable: true
  38018. });
  38019. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38020. /**
  38021. * Gets the midtones Exposure value.
  38022. * 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.
  38023. */
  38024. get: function () {
  38025. return this._midtonesExposure;
  38026. },
  38027. /**
  38028. * Sets the midtones Exposure value.
  38029. * 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.
  38030. */
  38031. set: function (value) {
  38032. this._midtonesExposure = value;
  38033. this._dirty = true;
  38034. },
  38035. enumerable: true,
  38036. configurable: true
  38037. });
  38038. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38039. /**
  38040. * Gets the shadows Hue value.
  38041. * 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).
  38042. */
  38043. get: function () {
  38044. return this._shadowsHue;
  38045. },
  38046. /**
  38047. * Sets the shadows Hue value.
  38048. * 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).
  38049. */
  38050. set: function (value) {
  38051. this._shadowsHue = value;
  38052. this._dirty = true;
  38053. },
  38054. enumerable: true,
  38055. configurable: true
  38056. });
  38057. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38058. /**
  38059. * Gets the shadows Density value.
  38060. * 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.
  38061. * Values less than zero provide a filter of opposite hue.
  38062. */
  38063. get: function () {
  38064. return this._shadowsDensity;
  38065. },
  38066. /**
  38067. * Sets the shadows Density value.
  38068. * 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.
  38069. * Values less than zero provide a filter of opposite hue.
  38070. */
  38071. set: function (value) {
  38072. this._shadowsDensity = value;
  38073. this._dirty = true;
  38074. },
  38075. enumerable: true,
  38076. configurable: true
  38077. });
  38078. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38079. /**
  38080. * Gets the shadows Saturation value.
  38081. * 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.
  38082. */
  38083. get: function () {
  38084. return this._shadowsSaturation;
  38085. },
  38086. /**
  38087. * Sets the shadows Saturation value.
  38088. * 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.
  38089. */
  38090. set: function (value) {
  38091. this._shadowsSaturation = value;
  38092. this._dirty = true;
  38093. },
  38094. enumerable: true,
  38095. configurable: true
  38096. });
  38097. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38098. /**
  38099. * Gets the shadows Exposure value.
  38100. * 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.
  38101. */
  38102. get: function () {
  38103. return this._shadowsExposure;
  38104. },
  38105. /**
  38106. * Sets the shadows Exposure value.
  38107. * 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.
  38108. */
  38109. set: function (value) {
  38110. this._shadowsExposure = value;
  38111. this._dirty = true;
  38112. },
  38113. enumerable: true,
  38114. configurable: true
  38115. });
  38116. ColorCurves.prototype.getClassName = function () {
  38117. return "ColorCurves";
  38118. };
  38119. /**
  38120. * Binds the color curves to the shader.
  38121. * @param colorCurves The color curve to bind
  38122. * @param effect The effect to bind to
  38123. */
  38124. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38125. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38126. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38127. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38128. if (colorCurves._dirty) {
  38129. colorCurves._dirty = false;
  38130. // Fill in global info.
  38131. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38132. // Compute highlights info.
  38133. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38134. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38135. // Compute midtones info.
  38136. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38137. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38138. // Compute shadows info.
  38139. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38140. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38141. // Compute deltas (neutral is midtones).
  38142. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38143. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38144. }
  38145. if (effect) {
  38146. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38147. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38148. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38149. }
  38150. };
  38151. /**
  38152. * Prepare the list of uniforms associated with the ColorCurves effects.
  38153. * @param uniformsList The list of uniforms used in the effect
  38154. */
  38155. ColorCurves.PrepareUniforms = function (uniformsList) {
  38156. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38157. };
  38158. /**
  38159. * Returns color grading data based on a hue, density, saturation and exposure value.
  38160. * @param filterHue The hue of the color filter.
  38161. * @param filterDensity The density of the color filter.
  38162. * @param saturation The saturation.
  38163. * @param exposure The exposure.
  38164. * @param result The result data container.
  38165. */
  38166. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38167. if (hue == null) {
  38168. return;
  38169. }
  38170. hue = ColorCurves.clamp(hue, 0, 360);
  38171. density = ColorCurves.clamp(density, -100, 100);
  38172. saturation = ColorCurves.clamp(saturation, -100, 100);
  38173. exposure = ColorCurves.clamp(exposure, -100, 100);
  38174. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38175. // so that the maximum filter density is only 50% control. This provides fine control
  38176. // for small values and reasonable range.
  38177. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38178. density *= 0.5;
  38179. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38180. if (density < 0) {
  38181. density *= -1;
  38182. hue = (hue + 180) % 360;
  38183. }
  38184. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38185. result.scaleToRef(2, result);
  38186. result.a = 1 + 0.01 * saturation;
  38187. };
  38188. /**
  38189. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38190. * @param value The input slider value in range [-100,100].
  38191. * @returns Adjusted value.
  38192. */
  38193. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38194. value /= 100;
  38195. var x = Math.abs(value);
  38196. x = Math.pow(x, 2);
  38197. if (value < 0) {
  38198. x *= -1;
  38199. }
  38200. x *= 100;
  38201. return x;
  38202. };
  38203. /**
  38204. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38205. * @param hue The hue (H) input.
  38206. * @param saturation The saturation (S) input.
  38207. * @param brightness The brightness (B) input.
  38208. * @result An RGBA color represented as Vector4.
  38209. */
  38210. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38211. var h = ColorCurves.clamp(hue, 0, 360);
  38212. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38213. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38214. if (s === 0) {
  38215. result.r = v;
  38216. result.g = v;
  38217. result.b = v;
  38218. }
  38219. else {
  38220. // sector 0 to 5
  38221. h /= 60;
  38222. var i = Math.floor(h);
  38223. // fractional part of h
  38224. var f = h - i;
  38225. var p = v * (1 - s);
  38226. var q = v * (1 - s * f);
  38227. var t = v * (1 - s * (1 - f));
  38228. switch (i) {
  38229. case 0:
  38230. result.r = v;
  38231. result.g = t;
  38232. result.b = p;
  38233. break;
  38234. case 1:
  38235. result.r = q;
  38236. result.g = v;
  38237. result.b = p;
  38238. break;
  38239. case 2:
  38240. result.r = p;
  38241. result.g = v;
  38242. result.b = t;
  38243. break;
  38244. case 3:
  38245. result.r = p;
  38246. result.g = q;
  38247. result.b = v;
  38248. break;
  38249. case 4:
  38250. result.r = t;
  38251. result.g = p;
  38252. result.b = v;
  38253. break;
  38254. default:// case 5:
  38255. result.r = v;
  38256. result.g = p;
  38257. result.b = q;
  38258. break;
  38259. }
  38260. }
  38261. result.a = 1;
  38262. };
  38263. /**
  38264. * Returns a value clamped between min and max
  38265. * @param value The value to clamp
  38266. * @param min The minimum of value
  38267. * @param max The maximum of value
  38268. * @returns The clamped value.
  38269. */
  38270. ColorCurves.clamp = function (value, min, max) {
  38271. return Math.min(Math.max(value, min), max);
  38272. };
  38273. /**
  38274. * Clones the current color curve instance.
  38275. * @return The cloned curves
  38276. */
  38277. ColorCurves.prototype.clone = function () {
  38278. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38279. };
  38280. /**
  38281. * Serializes the current color curve instance to a json representation.
  38282. * @return a JSON representation
  38283. */
  38284. ColorCurves.prototype.serialize = function () {
  38285. return BABYLON.SerializationHelper.Serialize(this);
  38286. };
  38287. /**
  38288. * Parses the color curve from a json representation.
  38289. * @param source the JSON source to parse
  38290. * @return The parsed curves
  38291. */
  38292. ColorCurves.Parse = function (source) {
  38293. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38294. };
  38295. __decorate([
  38296. BABYLON.serialize()
  38297. ], ColorCurves.prototype, "_globalHue", void 0);
  38298. __decorate([
  38299. BABYLON.serialize()
  38300. ], ColorCurves.prototype, "_globalDensity", void 0);
  38301. __decorate([
  38302. BABYLON.serialize()
  38303. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38304. __decorate([
  38305. BABYLON.serialize()
  38306. ], ColorCurves.prototype, "_globalExposure", void 0);
  38307. __decorate([
  38308. BABYLON.serialize()
  38309. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38310. __decorate([
  38311. BABYLON.serialize()
  38312. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38313. __decorate([
  38314. BABYLON.serialize()
  38315. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38316. __decorate([
  38317. BABYLON.serialize()
  38318. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38319. __decorate([
  38320. BABYLON.serialize()
  38321. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38322. __decorate([
  38323. BABYLON.serialize()
  38324. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38325. __decorate([
  38326. BABYLON.serialize()
  38327. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38328. __decorate([
  38329. BABYLON.serialize()
  38330. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38331. return ColorCurves;
  38332. }());
  38333. BABYLON.ColorCurves = ColorCurves;
  38334. })(BABYLON || (BABYLON = {}));
  38335. //# sourceMappingURL=babylon.colorCurves.js.map
  38336. //# sourceMappingURL=babylon.behavior.js.map
  38337. var BABYLON;
  38338. (function (BABYLON) {
  38339. /**
  38340. * "Static Class" containing the most commonly used helper while dealing with material for
  38341. * rendering purpose.
  38342. *
  38343. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38344. *
  38345. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38346. */
  38347. var MaterialHelper = /** @class */ (function () {
  38348. function MaterialHelper() {
  38349. }
  38350. /**
  38351. * Bind the current view position to an effect.
  38352. * @param effect The effect to be bound
  38353. * @param scene The scene the eyes position is used from
  38354. */
  38355. MaterialHelper.BindEyePosition = function (effect, scene) {
  38356. if (scene._forcedViewPosition) {
  38357. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38358. return;
  38359. }
  38360. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38361. };
  38362. /**
  38363. * Helps preparing the defines values about the UVs in used in the effect.
  38364. * UVs are shared as much as we can accross chanels in the shaders.
  38365. * @param texture The texture we are preparing the UVs for
  38366. * @param defines The defines to update
  38367. * @param key The chanel key "diffuse", "specular"... used in the shader
  38368. */
  38369. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38370. defines._needUVs = true;
  38371. defines[key] = true;
  38372. if (texture.getTextureMatrix().isIdentity(true)) {
  38373. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38374. if (texture.coordinatesIndex === 0) {
  38375. defines["MAINUV1"] = true;
  38376. }
  38377. else {
  38378. defines["MAINUV2"] = true;
  38379. }
  38380. }
  38381. else {
  38382. defines[key + "DIRECTUV"] = 0;
  38383. }
  38384. };
  38385. /**
  38386. * Binds a texture matrix value to its corrsponding uniform
  38387. * @param texture The texture to bind the matrix for
  38388. * @param uniformBuffer The uniform buffer receivin the data
  38389. * @param key The chanel key "diffuse", "specular"... used in the shader
  38390. */
  38391. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38392. var matrix = texture.getTextureMatrix();
  38393. if (!matrix.isIdentity(true)) {
  38394. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38395. }
  38396. };
  38397. /**
  38398. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38399. * @param mesh defines the current mesh
  38400. * @param scene defines the current scene
  38401. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38402. * @param pointsCloud defines if point cloud rendering has to be turned on
  38403. * @param fogEnabled defines if fog has to be turned on
  38404. * @param alphaTest defines if alpha testing has to be turned on
  38405. * @param defines defines the current list of defines
  38406. */
  38407. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38408. if (defines._areMiscDirty) {
  38409. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38410. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38411. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38412. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38413. defines["ALPHATEST"] = alphaTest;
  38414. }
  38415. };
  38416. /**
  38417. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38418. * @param scene defines the current scene
  38419. * @param engine defines the current engine
  38420. * @param defines specifies the list of active defines
  38421. * @param useInstances defines if instances have to be turned on
  38422. * @param useClipPlane defines if clip plane have to be turned on
  38423. */
  38424. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38425. if (useClipPlane === void 0) { useClipPlane = null; }
  38426. var changed = false;
  38427. if (useClipPlane == null) {
  38428. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38429. }
  38430. if (defines["CLIPPLANE"] !== useClipPlane) {
  38431. defines["CLIPPLANE"] = useClipPlane;
  38432. changed = true;
  38433. }
  38434. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38435. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38436. changed = true;
  38437. }
  38438. if (defines["INSTANCES"] !== useInstances) {
  38439. defines["INSTANCES"] = useInstances;
  38440. changed = true;
  38441. }
  38442. if (changed) {
  38443. defines.markAsUnprocessed();
  38444. }
  38445. };
  38446. /**
  38447. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38448. * @param mesh The mesh containing the geometry data we will draw
  38449. * @param defines The defines to update
  38450. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38451. * @param useBones Precise whether bones should be used or not (override mesh info)
  38452. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38453. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38454. * @returns false if defines are considered not dirty and have not been checked
  38455. */
  38456. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38457. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38458. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38459. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38460. return false;
  38461. }
  38462. defines._normals = defines._needNormals;
  38463. defines._uvs = defines._needUVs;
  38464. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38465. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38466. defines["TANGENT"] = true;
  38467. }
  38468. if (defines._needUVs) {
  38469. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38470. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38471. }
  38472. else {
  38473. defines["UV1"] = false;
  38474. defines["UV2"] = false;
  38475. }
  38476. if (useVertexColor) {
  38477. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38478. defines["VERTEXCOLOR"] = hasVertexColors;
  38479. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38480. }
  38481. if (useBones) {
  38482. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38483. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38484. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38485. }
  38486. else {
  38487. defines["NUM_BONE_INFLUENCERS"] = 0;
  38488. defines["BonesPerMesh"] = 0;
  38489. }
  38490. }
  38491. if (useMorphTargets) {
  38492. var manager = mesh.morphTargetManager;
  38493. if (manager) {
  38494. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38495. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38496. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38497. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38498. }
  38499. else {
  38500. defines["MORPHTARGETS_TANGENT"] = false;
  38501. defines["MORPHTARGETS_NORMAL"] = false;
  38502. defines["MORPHTARGETS"] = false;
  38503. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38504. }
  38505. }
  38506. return true;
  38507. };
  38508. /**
  38509. * Prepares the defines related to the light information passed in parameter
  38510. * @param scene The scene we are intending to draw
  38511. * @param mesh The mesh the effect is compiling for
  38512. * @param defines The defines to update
  38513. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38514. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38515. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38516. * @returns true if normals will be required for the rest of the effect
  38517. */
  38518. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38519. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38520. if (disableLighting === void 0) { disableLighting = false; }
  38521. if (!defines._areLightsDirty) {
  38522. return defines._needNormals;
  38523. }
  38524. var lightIndex = 0;
  38525. var needNormals = false;
  38526. var needRebuild = false;
  38527. var lightmapMode = false;
  38528. var shadowEnabled = false;
  38529. var specularEnabled = false;
  38530. if (scene.lightsEnabled && !disableLighting) {
  38531. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38532. var light = _a[_i];
  38533. needNormals = true;
  38534. if (defines["LIGHT" + lightIndex] === undefined) {
  38535. needRebuild = true;
  38536. }
  38537. defines["LIGHT" + lightIndex] = true;
  38538. defines["SPOTLIGHT" + lightIndex] = false;
  38539. defines["HEMILIGHT" + lightIndex] = false;
  38540. defines["POINTLIGHT" + lightIndex] = false;
  38541. defines["DIRLIGHT" + lightIndex] = false;
  38542. var type;
  38543. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38544. type = "SPOTLIGHT" + lightIndex;
  38545. var spotLight = light;
  38546. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38547. }
  38548. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38549. type = "HEMILIGHT" + lightIndex;
  38550. }
  38551. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38552. type = "POINTLIGHT" + lightIndex;
  38553. }
  38554. else {
  38555. type = "DIRLIGHT" + lightIndex;
  38556. }
  38557. defines[type] = true;
  38558. // Specular
  38559. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38560. specularEnabled = true;
  38561. }
  38562. // Shadows
  38563. defines["SHADOW" + lightIndex] = false;
  38564. defines["SHADOWPCF" + lightIndex] = false;
  38565. defines["SHADOWESM" + lightIndex] = false;
  38566. defines["SHADOWCUBE" + lightIndex] = false;
  38567. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38568. var shadowGenerator = light.getShadowGenerator();
  38569. if (shadowGenerator) {
  38570. shadowEnabled = true;
  38571. shadowGenerator.prepareDefines(defines, lightIndex);
  38572. }
  38573. }
  38574. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38575. lightmapMode = true;
  38576. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38577. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38578. }
  38579. else {
  38580. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38581. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38582. }
  38583. lightIndex++;
  38584. if (lightIndex === maxSimultaneousLights)
  38585. break;
  38586. }
  38587. }
  38588. defines["SPECULARTERM"] = specularEnabled;
  38589. defines["SHADOWS"] = shadowEnabled;
  38590. // Resetting all other lights if any
  38591. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38592. if (defines["LIGHT" + index] !== undefined) {
  38593. defines["LIGHT" + index] = false;
  38594. defines["HEMILIGHT" + lightIndex] = false;
  38595. defines["POINTLIGHT" + lightIndex] = false;
  38596. defines["DIRLIGHT" + lightIndex] = false;
  38597. defines["SPOTLIGHT" + lightIndex] = false;
  38598. defines["SHADOW" + lightIndex] = false;
  38599. }
  38600. }
  38601. var caps = scene.getEngine().getCaps();
  38602. if (defines["SHADOWFLOAT"] === undefined) {
  38603. needRebuild = true;
  38604. }
  38605. defines["SHADOWFLOAT"] = shadowEnabled &&
  38606. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38607. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38608. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38609. if (needRebuild) {
  38610. defines.rebuild();
  38611. }
  38612. return needNormals;
  38613. };
  38614. /**
  38615. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38616. * that won t be acctive due to defines being turned off.
  38617. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38618. * @param samplersList The samplers list
  38619. * @param defines The defines helping in the list generation
  38620. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38621. */
  38622. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38623. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38624. var uniformsList;
  38625. var uniformBuffersList = null;
  38626. if (uniformsListOrOptions.uniformsNames) {
  38627. var options = uniformsListOrOptions;
  38628. uniformsList = options.uniformsNames;
  38629. uniformBuffersList = options.uniformBuffersNames;
  38630. samplersList = options.samplers;
  38631. defines = options.defines;
  38632. maxSimultaneousLights = options.maxSimultaneousLights;
  38633. }
  38634. else {
  38635. uniformsList = uniformsListOrOptions;
  38636. if (!samplersList) {
  38637. samplersList = [];
  38638. }
  38639. }
  38640. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38641. if (!defines["LIGHT" + lightIndex]) {
  38642. break;
  38643. }
  38644. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38645. if (uniformBuffersList) {
  38646. uniformBuffersList.push("Light" + lightIndex);
  38647. }
  38648. samplersList.push("shadowSampler" + lightIndex);
  38649. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38650. samplersList.push("projectionLightSampler" + lightIndex);
  38651. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38652. }
  38653. }
  38654. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38655. uniformsList.push("morphTargetInfluences");
  38656. }
  38657. };
  38658. /**
  38659. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38660. * @param defines The defines to update while falling back
  38661. * @param fallbacks The authorized effect fallbacks
  38662. * @param maxSimultaneousLights The maximum number of lights allowed
  38663. * @param rank the current rank of the Effect
  38664. * @returns The newly affected rank
  38665. */
  38666. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38667. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38668. if (rank === void 0) { rank = 0; }
  38669. var lightFallbackRank = 0;
  38670. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38671. if (!defines["LIGHT" + lightIndex]) {
  38672. break;
  38673. }
  38674. if (lightIndex > 0) {
  38675. lightFallbackRank = rank + lightIndex;
  38676. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38677. }
  38678. if (!defines["SHADOWS"]) {
  38679. if (defines["SHADOW" + lightIndex]) {
  38680. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38681. }
  38682. if (defines["SHADOWPCF" + lightIndex]) {
  38683. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38684. }
  38685. if (defines["SHADOWESM" + lightIndex]) {
  38686. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38687. }
  38688. }
  38689. }
  38690. return lightFallbackRank++;
  38691. };
  38692. /**
  38693. * Prepares the list of attributes required for morph targets according to the effect defines.
  38694. * @param attribs The current list of supported attribs
  38695. * @param mesh The mesh to prepare the morph targets attributes for
  38696. * @param defines The current Defines of the effect
  38697. */
  38698. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38699. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38700. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38701. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38702. var manager = mesh.morphTargetManager;
  38703. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38704. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38705. for (var index = 0; index < influencers; index++) {
  38706. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38707. if (normal) {
  38708. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38709. }
  38710. if (tangent) {
  38711. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38712. }
  38713. if (attribs.length > maxAttributesCount) {
  38714. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38715. }
  38716. }
  38717. }
  38718. };
  38719. /**
  38720. * Prepares the list of attributes required for bones according to the effect defines.
  38721. * @param attribs The current list of supported attribs
  38722. * @param mesh The mesh to prepare the bones attributes for
  38723. * @param defines The current Defines of the effect
  38724. * @param fallbacks The current efffect fallback strategy
  38725. */
  38726. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38727. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38728. fallbacks.addCPUSkinningFallback(0, mesh);
  38729. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38730. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38731. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38732. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38733. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38734. }
  38735. }
  38736. };
  38737. /**
  38738. * Prepares the list of attributes required for instances according to the effect defines.
  38739. * @param attribs The current list of supported attribs
  38740. * @param defines The current Defines of the effect
  38741. */
  38742. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38743. if (defines["INSTANCES"]) {
  38744. attribs.push("world0");
  38745. attribs.push("world1");
  38746. attribs.push("world2");
  38747. attribs.push("world3");
  38748. }
  38749. };
  38750. /**
  38751. * Binds the light shadow information to the effect for the given mesh.
  38752. * @param light The light containing the generator
  38753. * @param scene The scene the lights belongs to
  38754. * @param mesh The mesh we are binding the information to render
  38755. * @param lightIndex The light index in the effect used to render the mesh
  38756. * @param effect The effect we are binding the data to
  38757. */
  38758. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38759. if (light.shadowEnabled && mesh.receiveShadows) {
  38760. var shadowGenerator = light.getShadowGenerator();
  38761. if (shadowGenerator) {
  38762. shadowGenerator.bindShadowLight(lightIndex, effect);
  38763. }
  38764. }
  38765. };
  38766. /**
  38767. * Binds the light information to the effect.
  38768. * @param light The light containing the generator
  38769. * @param effect The effect we are binding the data to
  38770. * @param lightIndex The light index in the effect used to render
  38771. */
  38772. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38773. light.transferToEffect(effect, lightIndex + "");
  38774. };
  38775. /**
  38776. * Binds the lights information from the scene to the effect for the given mesh.
  38777. * @param scene The scene the lights belongs to
  38778. * @param mesh The mesh we are binding the information to render
  38779. * @param effect The effect we are binding the data to
  38780. * @param defines The generated defines for the effect
  38781. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38782. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38783. */
  38784. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38785. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38786. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38787. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38788. for (var i = 0; i < len; i++) {
  38789. var light = mesh._lightSources[i];
  38790. var iAsString = i.toString();
  38791. var scaledIntensity = light.getScaledIntensity();
  38792. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38793. MaterialHelper.BindLightProperties(light, effect, i);
  38794. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38795. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38796. if (defines["SPECULARTERM"]) {
  38797. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38798. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38799. }
  38800. // Shadows
  38801. if (scene.shadowsEnabled) {
  38802. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38803. }
  38804. light._uniformBuffer.update();
  38805. }
  38806. };
  38807. /**
  38808. * Binds the fog information from the scene to the effect for the given mesh.
  38809. * @param scene The scene the lights belongs to
  38810. * @param mesh The mesh we are binding the information to render
  38811. * @param effect The effect we are binding the data to
  38812. */
  38813. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38814. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38815. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38816. effect.setColor3("vFogColor", scene.fogColor);
  38817. }
  38818. };
  38819. /**
  38820. * Binds the bones information from the mesh to the effect.
  38821. * @param mesh The mesh we are binding the information to render
  38822. * @param effect The effect we are binding the data to
  38823. */
  38824. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38825. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38826. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38827. if (matrices && effect) {
  38828. effect.setMatrices("mBones", matrices);
  38829. }
  38830. }
  38831. };
  38832. /**
  38833. * Binds the morph targets information from the mesh to the effect.
  38834. * @param abstractMesh The mesh we are binding the information to render
  38835. * @param effect The effect we are binding the data to
  38836. */
  38837. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38838. var manager = abstractMesh.morphTargetManager;
  38839. if (!abstractMesh || !manager) {
  38840. return;
  38841. }
  38842. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38843. };
  38844. /**
  38845. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38846. * @param defines The generated defines used in the effect
  38847. * @param effect The effect we are binding the data to
  38848. * @param scene The scene we are willing to render with logarithmic scale for
  38849. */
  38850. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38851. if (defines["LOGARITHMICDEPTH"]) {
  38852. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38853. }
  38854. };
  38855. /**
  38856. * Binds the clip plane information from the scene to the effect.
  38857. * @param scene The scene the clip plane information are extracted from
  38858. * @param effect The effect we are binding the data to
  38859. */
  38860. MaterialHelper.BindClipPlane = function (effect, scene) {
  38861. if (scene.clipPlane) {
  38862. var clipPlane = scene.clipPlane;
  38863. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38864. }
  38865. };
  38866. return MaterialHelper;
  38867. }());
  38868. BABYLON.MaterialHelper = MaterialHelper;
  38869. })(BABYLON || (BABYLON = {}));
  38870. //# sourceMappingURL=babylon.materialHelper.js.map
  38871. var BABYLON;
  38872. (function (BABYLON) {
  38873. var PushMaterial = /** @class */ (function (_super) {
  38874. __extends(PushMaterial, _super);
  38875. function PushMaterial(name, scene) {
  38876. var _this = _super.call(this, name, scene) || this;
  38877. _this._normalMatrix = new BABYLON.Matrix();
  38878. _this.storeEffectOnSubMeshes = true;
  38879. return _this;
  38880. }
  38881. PushMaterial.prototype.getEffect = function () {
  38882. return this._activeEffect;
  38883. };
  38884. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38885. if (!mesh) {
  38886. return false;
  38887. }
  38888. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38889. return true;
  38890. }
  38891. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38892. };
  38893. /**
  38894. * Binds the given world matrix to the active effect
  38895. *
  38896. * @param world the matrix to bind
  38897. */
  38898. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38899. this._activeEffect.setMatrix("world", world);
  38900. };
  38901. /**
  38902. * Binds the given normal matrix to the active effect
  38903. *
  38904. * @param normalMatrix the matrix to bind
  38905. */
  38906. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38907. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38908. };
  38909. PushMaterial.prototype.bind = function (world, mesh) {
  38910. if (!mesh) {
  38911. return;
  38912. }
  38913. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38914. };
  38915. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38916. if (effect === void 0) { effect = null; }
  38917. _super.prototype._afterBind.call(this, mesh);
  38918. this.getScene()._cachedEffect = effect;
  38919. };
  38920. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38921. if (visibility === void 0) { visibility = 1; }
  38922. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38923. };
  38924. return PushMaterial;
  38925. }(BABYLON.Material));
  38926. BABYLON.PushMaterial = PushMaterial;
  38927. })(BABYLON || (BABYLON = {}));
  38928. //# sourceMappingURL=babylon.pushMaterial.js.map
  38929. var BABYLON;
  38930. (function (BABYLON) {
  38931. /** @ignore */
  38932. var StandardMaterialDefines = /** @class */ (function (_super) {
  38933. __extends(StandardMaterialDefines, _super);
  38934. function StandardMaterialDefines() {
  38935. var _this = _super.call(this) || this;
  38936. _this.MAINUV1 = false;
  38937. _this.MAINUV2 = false;
  38938. _this.DIFFUSE = false;
  38939. _this.DIFFUSEDIRECTUV = 0;
  38940. _this.AMBIENT = false;
  38941. _this.AMBIENTDIRECTUV = 0;
  38942. _this.OPACITY = false;
  38943. _this.OPACITYDIRECTUV = 0;
  38944. _this.OPACITYRGB = false;
  38945. _this.REFLECTION = false;
  38946. _this.EMISSIVE = false;
  38947. _this.EMISSIVEDIRECTUV = 0;
  38948. _this.SPECULAR = false;
  38949. _this.SPECULARDIRECTUV = 0;
  38950. _this.BUMP = false;
  38951. _this.BUMPDIRECTUV = 0;
  38952. _this.PARALLAX = false;
  38953. _this.PARALLAXOCCLUSION = false;
  38954. _this.SPECULAROVERALPHA = false;
  38955. _this.CLIPPLANE = false;
  38956. _this.ALPHATEST = false;
  38957. _this.DEPTHPREPASS = false;
  38958. _this.ALPHAFROMDIFFUSE = false;
  38959. _this.POINTSIZE = false;
  38960. _this.FOG = false;
  38961. _this.SPECULARTERM = false;
  38962. _this.DIFFUSEFRESNEL = false;
  38963. _this.OPACITYFRESNEL = false;
  38964. _this.REFLECTIONFRESNEL = false;
  38965. _this.REFRACTIONFRESNEL = false;
  38966. _this.EMISSIVEFRESNEL = false;
  38967. _this.FRESNEL = false;
  38968. _this.NORMAL = false;
  38969. _this.UV1 = false;
  38970. _this.UV2 = false;
  38971. _this.VERTEXCOLOR = false;
  38972. _this.VERTEXALPHA = false;
  38973. _this.NUM_BONE_INFLUENCERS = 0;
  38974. _this.BonesPerMesh = 0;
  38975. _this.INSTANCES = false;
  38976. _this.GLOSSINESS = false;
  38977. _this.ROUGHNESS = false;
  38978. _this.EMISSIVEASILLUMINATION = false;
  38979. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38980. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38981. _this.LIGHTMAP = false;
  38982. _this.LIGHTMAPDIRECTUV = 0;
  38983. _this.OBJECTSPACE_NORMALMAP = false;
  38984. _this.USELIGHTMAPASSHADOWMAP = false;
  38985. _this.REFLECTIONMAP_3D = false;
  38986. _this.REFLECTIONMAP_SPHERICAL = false;
  38987. _this.REFLECTIONMAP_PLANAR = false;
  38988. _this.REFLECTIONMAP_CUBIC = false;
  38989. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38990. _this.REFLECTIONMAP_PROJECTION = false;
  38991. _this.REFLECTIONMAP_SKYBOX = false;
  38992. _this.REFLECTIONMAP_EXPLICIT = false;
  38993. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38994. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38995. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38996. _this.INVERTCUBICMAP = false;
  38997. _this.LOGARITHMICDEPTH = false;
  38998. _this.REFRACTION = false;
  38999. _this.REFRACTIONMAP_3D = false;
  39000. _this.REFLECTIONOVERALPHA = false;
  39001. _this.TWOSIDEDLIGHTING = false;
  39002. _this.SHADOWFLOAT = false;
  39003. _this.MORPHTARGETS = false;
  39004. _this.MORPHTARGETS_NORMAL = false;
  39005. _this.MORPHTARGETS_TANGENT = false;
  39006. _this.NUM_MORPH_INFLUENCERS = 0;
  39007. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39008. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39009. _this.IMAGEPROCESSING = false;
  39010. _this.VIGNETTE = false;
  39011. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39012. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39013. _this.TONEMAPPING = false;
  39014. _this.CONTRAST = false;
  39015. _this.COLORCURVES = false;
  39016. _this.COLORGRADING = false;
  39017. _this.COLORGRADING3D = false;
  39018. _this.SAMPLER3DGREENDEPTH = false;
  39019. _this.SAMPLER3DBGRMAP = false;
  39020. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39021. _this.EXPOSURE = false;
  39022. _this.GRAIN = false;
  39023. _this.rebuild();
  39024. return _this;
  39025. }
  39026. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39027. var modes = [
  39028. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39029. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39030. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39031. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39032. ];
  39033. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39034. var mode = modes_1[_i];
  39035. this[mode] = (mode === modeToEnable);
  39036. }
  39037. };
  39038. return StandardMaterialDefines;
  39039. }(BABYLON.MaterialDefines));
  39040. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39041. var StandardMaterial = /** @class */ (function (_super) {
  39042. __extends(StandardMaterial, _super);
  39043. function StandardMaterial(name, scene) {
  39044. var _this = _super.call(this, name, scene) || this;
  39045. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39046. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39047. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39048. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39049. _this.specularPower = 64;
  39050. _this._useAlphaFromDiffuseTexture = false;
  39051. _this._useEmissiveAsIllumination = false;
  39052. _this._linkEmissiveWithDiffuse = false;
  39053. _this._useSpecularOverAlpha = false;
  39054. _this._useReflectionOverAlpha = false;
  39055. _this._disableLighting = false;
  39056. _this._useObjectSpaceNormalMap = false;
  39057. _this._useParallax = false;
  39058. _this._useParallaxOcclusion = false;
  39059. _this.parallaxScaleBias = 0.05;
  39060. _this._roughness = 0;
  39061. _this.indexOfRefraction = 0.98;
  39062. _this.invertRefractionY = true;
  39063. _this._useLightmapAsShadowmap = false;
  39064. _this._useReflectionFresnelFromSpecular = false;
  39065. _this._useGlossinessFromSpecularMapAlpha = false;
  39066. _this._maxSimultaneousLights = 4;
  39067. /**
  39068. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39069. */
  39070. _this._invertNormalMapX = false;
  39071. /**
  39072. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39073. */
  39074. _this._invertNormalMapY = false;
  39075. /**
  39076. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39077. */
  39078. _this._twoSidedLighting = false;
  39079. _this._renderTargets = new BABYLON.SmartArray(16);
  39080. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39081. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39082. // Setup the default processing configuration to the scene.
  39083. _this._attachImageProcessingConfiguration(null);
  39084. _this.getRenderTargetTextures = function () {
  39085. _this._renderTargets.reset();
  39086. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39087. _this._renderTargets.push(_this._reflectionTexture);
  39088. }
  39089. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39090. _this._renderTargets.push(_this._refractionTexture);
  39091. }
  39092. return _this._renderTargets;
  39093. };
  39094. return _this;
  39095. }
  39096. ;
  39097. ;
  39098. ;
  39099. ;
  39100. ;
  39101. ;
  39102. ;
  39103. ;
  39104. ;
  39105. ;
  39106. ;
  39107. ;
  39108. ;
  39109. ;
  39110. ;
  39111. ;
  39112. ;
  39113. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39114. /**
  39115. * Gets the image processing configuration used either in this material.
  39116. */
  39117. get: function () {
  39118. return this._imageProcessingConfiguration;
  39119. },
  39120. /**
  39121. * Sets the Default image processing configuration used either in the this material.
  39122. *
  39123. * If sets to null, the scene one is in use.
  39124. */
  39125. set: function (value) {
  39126. this._attachImageProcessingConfiguration(value);
  39127. // Ensure the effect will be rebuilt.
  39128. this._markAllSubMeshesAsTexturesDirty();
  39129. },
  39130. enumerable: true,
  39131. configurable: true
  39132. });
  39133. /**
  39134. * Attaches a new image processing configuration to the Standard Material.
  39135. * @param configuration
  39136. */
  39137. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39138. var _this = this;
  39139. if (configuration === this._imageProcessingConfiguration) {
  39140. return;
  39141. }
  39142. // Detaches observer.
  39143. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39144. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39145. }
  39146. // Pick the scene configuration if needed.
  39147. if (!configuration) {
  39148. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39149. }
  39150. else {
  39151. this._imageProcessingConfiguration = configuration;
  39152. }
  39153. // Attaches observer.
  39154. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39155. _this._markAllSubMeshesAsImageProcessingDirty();
  39156. });
  39157. };
  39158. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39159. /**
  39160. * Gets wether the color curves effect is enabled.
  39161. */
  39162. get: function () {
  39163. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39164. },
  39165. /**
  39166. * Sets wether the color curves effect is enabled.
  39167. */
  39168. set: function (value) {
  39169. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39170. },
  39171. enumerable: true,
  39172. configurable: true
  39173. });
  39174. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39175. /**
  39176. * Gets wether the color grading effect is enabled.
  39177. */
  39178. get: function () {
  39179. return this.imageProcessingConfiguration.colorGradingEnabled;
  39180. },
  39181. /**
  39182. * Gets wether the color grading effect is enabled.
  39183. */
  39184. set: function (value) {
  39185. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39186. },
  39187. enumerable: true,
  39188. configurable: true
  39189. });
  39190. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39191. /**
  39192. * Gets wether tonemapping is enabled or not.
  39193. */
  39194. get: function () {
  39195. return this._imageProcessingConfiguration.toneMappingEnabled;
  39196. },
  39197. /**
  39198. * Sets wether tonemapping is enabled or not
  39199. */
  39200. set: function (value) {
  39201. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39202. },
  39203. enumerable: true,
  39204. configurable: true
  39205. });
  39206. ;
  39207. ;
  39208. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39209. /**
  39210. * The camera exposure used on this material.
  39211. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39212. * This corresponds to a photographic exposure.
  39213. */
  39214. get: function () {
  39215. return this._imageProcessingConfiguration.exposure;
  39216. },
  39217. /**
  39218. * The camera exposure used on this material.
  39219. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39220. * This corresponds to a photographic exposure.
  39221. */
  39222. set: function (value) {
  39223. this._imageProcessingConfiguration.exposure = value;
  39224. },
  39225. enumerable: true,
  39226. configurable: true
  39227. });
  39228. ;
  39229. ;
  39230. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39231. /**
  39232. * Gets The camera contrast used on this material.
  39233. */
  39234. get: function () {
  39235. return this._imageProcessingConfiguration.contrast;
  39236. },
  39237. /**
  39238. * Sets The camera contrast used on this material.
  39239. */
  39240. set: function (value) {
  39241. this._imageProcessingConfiguration.contrast = value;
  39242. },
  39243. enumerable: true,
  39244. configurable: true
  39245. });
  39246. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39247. /**
  39248. * Gets the Color Grading 2D Lookup Texture.
  39249. */
  39250. get: function () {
  39251. return this._imageProcessingConfiguration.colorGradingTexture;
  39252. },
  39253. /**
  39254. * Sets the Color Grading 2D Lookup Texture.
  39255. */
  39256. set: function (value) {
  39257. this._imageProcessingConfiguration.colorGradingTexture = value;
  39258. },
  39259. enumerable: true,
  39260. configurable: true
  39261. });
  39262. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39263. /**
  39264. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39265. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39266. * 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;
  39267. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39268. */
  39269. get: function () {
  39270. return this._imageProcessingConfiguration.colorCurves;
  39271. },
  39272. /**
  39273. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39274. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39275. * 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;
  39276. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39277. */
  39278. set: function (value) {
  39279. this._imageProcessingConfiguration.colorCurves = value;
  39280. },
  39281. enumerable: true,
  39282. configurable: true
  39283. });
  39284. StandardMaterial.prototype.getClassName = function () {
  39285. return "StandardMaterial";
  39286. };
  39287. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39288. get: function () {
  39289. return this._useLogarithmicDepth;
  39290. },
  39291. set: function (value) {
  39292. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39293. this._markAllSubMeshesAsMiscDirty();
  39294. },
  39295. enumerable: true,
  39296. configurable: true
  39297. });
  39298. StandardMaterial.prototype.needAlphaBlending = function () {
  39299. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39300. };
  39301. StandardMaterial.prototype.needAlphaTesting = function () {
  39302. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39303. };
  39304. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39305. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39306. };
  39307. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39308. return this._diffuseTexture;
  39309. };
  39310. /**
  39311. * Child classes can use it to update shaders
  39312. */
  39313. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39314. if (useInstances === void 0) { useInstances = false; }
  39315. if (subMesh.effect && this.isFrozen) {
  39316. if (this._wasPreviouslyReady && subMesh.effect) {
  39317. return true;
  39318. }
  39319. }
  39320. if (!subMesh._materialDefines) {
  39321. subMesh._materialDefines = new StandardMaterialDefines();
  39322. }
  39323. var scene = this.getScene();
  39324. var defines = subMesh._materialDefines;
  39325. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39326. if (defines._renderId === scene.getRenderId()) {
  39327. return true;
  39328. }
  39329. }
  39330. var engine = scene.getEngine();
  39331. // Lights
  39332. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39333. // Textures
  39334. if (defines._areTexturesDirty) {
  39335. defines._needUVs = false;
  39336. defines.MAINUV1 = false;
  39337. defines.MAINUV2 = false;
  39338. if (scene.texturesEnabled) {
  39339. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39340. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39341. return false;
  39342. }
  39343. else {
  39344. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39345. }
  39346. }
  39347. else {
  39348. defines.DIFFUSE = false;
  39349. }
  39350. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39351. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39352. return false;
  39353. }
  39354. else {
  39355. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39356. }
  39357. }
  39358. else {
  39359. defines.AMBIENT = false;
  39360. }
  39361. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39362. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39363. return false;
  39364. }
  39365. else {
  39366. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39367. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39368. }
  39369. }
  39370. else {
  39371. defines.OPACITY = false;
  39372. }
  39373. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39374. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39375. return false;
  39376. }
  39377. else {
  39378. defines._needNormals = true;
  39379. defines.REFLECTION = true;
  39380. defines.ROUGHNESS = (this._roughness > 0);
  39381. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39382. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39383. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39384. switch (this._reflectionTexture.coordinatesMode) {
  39385. case BABYLON.Texture.CUBIC_MODE:
  39386. case BABYLON.Texture.INVCUBIC_MODE:
  39387. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39388. break;
  39389. case BABYLON.Texture.EXPLICIT_MODE:
  39390. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39391. break;
  39392. case BABYLON.Texture.PLANAR_MODE:
  39393. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39394. break;
  39395. case BABYLON.Texture.PROJECTION_MODE:
  39396. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39397. break;
  39398. case BABYLON.Texture.SKYBOX_MODE:
  39399. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39400. break;
  39401. case BABYLON.Texture.SPHERICAL_MODE:
  39402. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39403. break;
  39404. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39405. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39406. break;
  39407. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39408. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39409. break;
  39410. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39411. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39412. break;
  39413. }
  39414. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39415. }
  39416. }
  39417. else {
  39418. defines.REFLECTION = false;
  39419. }
  39420. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39421. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39422. return false;
  39423. }
  39424. else {
  39425. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39426. }
  39427. }
  39428. else {
  39429. defines.EMISSIVE = false;
  39430. }
  39431. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39432. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39433. return false;
  39434. }
  39435. else {
  39436. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39437. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39438. }
  39439. }
  39440. else {
  39441. defines.LIGHTMAP = false;
  39442. }
  39443. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39444. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39445. return false;
  39446. }
  39447. else {
  39448. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39449. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39450. }
  39451. }
  39452. else {
  39453. defines.SPECULAR = false;
  39454. }
  39455. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39456. // Bump texure can not be not blocking.
  39457. if (!this._bumpTexture.isReady()) {
  39458. return false;
  39459. }
  39460. else {
  39461. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39462. defines.PARALLAX = this._useParallax;
  39463. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39464. }
  39465. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39466. }
  39467. else {
  39468. defines.BUMP = false;
  39469. }
  39470. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39471. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39472. return false;
  39473. }
  39474. else {
  39475. defines._needUVs = true;
  39476. defines.REFRACTION = true;
  39477. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39478. }
  39479. }
  39480. else {
  39481. defines.REFRACTION = false;
  39482. }
  39483. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39484. }
  39485. else {
  39486. defines.DIFFUSE = false;
  39487. defines.AMBIENT = false;
  39488. defines.OPACITY = false;
  39489. defines.REFLECTION = false;
  39490. defines.EMISSIVE = false;
  39491. defines.LIGHTMAP = false;
  39492. defines.BUMP = false;
  39493. defines.REFRACTION = false;
  39494. }
  39495. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39496. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39497. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39498. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39499. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39500. }
  39501. if (defines._areImageProcessingDirty) {
  39502. if (!this._imageProcessingConfiguration.isReady()) {
  39503. return false;
  39504. }
  39505. this._imageProcessingConfiguration.prepareDefines(defines);
  39506. }
  39507. if (defines._areFresnelDirty) {
  39508. if (StandardMaterial.FresnelEnabled) {
  39509. // Fresnel
  39510. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39511. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39512. this._reflectionFresnelParameters) {
  39513. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39514. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39515. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39516. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39517. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39518. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39519. defines._needNormals = true;
  39520. defines.FRESNEL = true;
  39521. }
  39522. }
  39523. else {
  39524. defines.FRESNEL = false;
  39525. }
  39526. }
  39527. // Misc.
  39528. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39529. // Attribs
  39530. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39531. // Values that need to be evaluated on every frame
  39532. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39533. // Get correct effect
  39534. if (defines.isDirty) {
  39535. defines.markAsProcessed();
  39536. scene.resetCachedMaterial();
  39537. // Fallbacks
  39538. var fallbacks = new BABYLON.EffectFallbacks();
  39539. if (defines.REFLECTION) {
  39540. fallbacks.addFallback(0, "REFLECTION");
  39541. }
  39542. if (defines.SPECULAR) {
  39543. fallbacks.addFallback(0, "SPECULAR");
  39544. }
  39545. if (defines.BUMP) {
  39546. fallbacks.addFallback(0, "BUMP");
  39547. }
  39548. if (defines.PARALLAX) {
  39549. fallbacks.addFallback(1, "PARALLAX");
  39550. }
  39551. if (defines.PARALLAXOCCLUSION) {
  39552. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39553. }
  39554. if (defines.SPECULAROVERALPHA) {
  39555. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39556. }
  39557. if (defines.FOG) {
  39558. fallbacks.addFallback(1, "FOG");
  39559. }
  39560. if (defines.POINTSIZE) {
  39561. fallbacks.addFallback(0, "POINTSIZE");
  39562. }
  39563. if (defines.LOGARITHMICDEPTH) {
  39564. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39565. }
  39566. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39567. if (defines.SPECULARTERM) {
  39568. fallbacks.addFallback(0, "SPECULARTERM");
  39569. }
  39570. if (defines.DIFFUSEFRESNEL) {
  39571. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39572. }
  39573. if (defines.OPACITYFRESNEL) {
  39574. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39575. }
  39576. if (defines.REFLECTIONFRESNEL) {
  39577. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39578. }
  39579. if (defines.EMISSIVEFRESNEL) {
  39580. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39581. }
  39582. if (defines.FRESNEL) {
  39583. fallbacks.addFallback(4, "FRESNEL");
  39584. }
  39585. //Attributes
  39586. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39587. if (defines.NORMAL) {
  39588. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39589. }
  39590. if (defines.UV1) {
  39591. attribs.push(BABYLON.VertexBuffer.UVKind);
  39592. }
  39593. if (defines.UV2) {
  39594. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39595. }
  39596. if (defines.VERTEXCOLOR) {
  39597. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39598. }
  39599. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39600. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39601. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39602. var shaderName = "default";
  39603. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39604. "vFogInfos", "vFogColor", "pointSize",
  39605. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39606. "mBones",
  39607. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39608. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39609. "vReflectionPosition", "vReflectionSize",
  39610. "logarithmicDepthConstant", "vTangentSpaceParams"
  39611. ];
  39612. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39613. var uniformBuffers = ["Material", "Scene"];
  39614. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39615. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39616. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39617. uniformsNames: uniforms,
  39618. uniformBuffersNames: uniformBuffers,
  39619. samplers: samplers,
  39620. defines: defines,
  39621. maxSimultaneousLights: this._maxSimultaneousLights
  39622. });
  39623. if (this.customShaderNameResolve) {
  39624. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39625. }
  39626. var join = defines.toString();
  39627. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39628. attributes: attribs,
  39629. uniformsNames: uniforms,
  39630. uniformBuffersNames: uniformBuffers,
  39631. samplers: samplers,
  39632. defines: join,
  39633. fallbacks: fallbacks,
  39634. onCompiled: this.onCompiled,
  39635. onError: this.onError,
  39636. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39637. }, engine), defines);
  39638. this.buildUniformLayout();
  39639. }
  39640. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39641. return false;
  39642. }
  39643. defines._renderId = scene.getRenderId();
  39644. this._wasPreviouslyReady = true;
  39645. return true;
  39646. };
  39647. StandardMaterial.prototype.buildUniformLayout = function () {
  39648. // Order is important !
  39649. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39650. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39651. this._uniformBuffer.addUniform("opacityParts", 4);
  39652. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39653. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39654. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39655. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39656. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39657. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39658. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39659. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39660. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39661. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39662. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39663. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39664. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39665. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39666. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39667. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39668. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39669. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39670. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39671. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39672. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39673. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39674. this._uniformBuffer.addUniform("specularMatrix", 16);
  39675. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39676. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39677. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39678. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39679. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39680. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39681. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39682. this._uniformBuffer.addUniform("pointSize", 1);
  39683. this._uniformBuffer.create();
  39684. };
  39685. StandardMaterial.prototype.unbind = function () {
  39686. if (this._activeEffect) {
  39687. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39688. this._activeEffect.setTexture("reflection2DSampler", null);
  39689. }
  39690. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39691. this._activeEffect.setTexture("refraction2DSampler", null);
  39692. }
  39693. }
  39694. _super.prototype.unbind.call(this);
  39695. };
  39696. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39697. var scene = this.getScene();
  39698. var defines = subMesh._materialDefines;
  39699. if (!defines) {
  39700. return;
  39701. }
  39702. var effect = subMesh.effect;
  39703. if (!effect) {
  39704. return;
  39705. }
  39706. this._activeEffect = effect;
  39707. // Matrices
  39708. this.bindOnlyWorldMatrix(world);
  39709. // Normal Matrix
  39710. if (defines.OBJECTSPACE_NORMALMAP) {
  39711. world.toNormalMatrix(this._normalMatrix);
  39712. this.bindOnlyNormalMatrix(this._normalMatrix);
  39713. }
  39714. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39715. // Bones
  39716. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39717. if (mustRebind) {
  39718. this._uniformBuffer.bindToEffect(effect, "Material");
  39719. this.bindViewProjection(effect);
  39720. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39721. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39722. // Fresnel
  39723. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39724. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39725. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39726. }
  39727. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39728. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39729. }
  39730. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39731. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39732. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39733. }
  39734. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39735. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39736. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39737. }
  39738. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39739. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39740. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39741. }
  39742. }
  39743. // Textures
  39744. if (scene.texturesEnabled) {
  39745. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39746. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39747. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39748. }
  39749. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39750. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39751. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39752. }
  39753. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39754. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39755. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39756. }
  39757. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39758. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39759. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39760. if (this._reflectionTexture.boundingBoxSize) {
  39761. var cubeTexture = this._reflectionTexture;
  39762. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39763. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39764. }
  39765. }
  39766. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39767. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39768. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39769. }
  39770. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39771. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39772. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39773. }
  39774. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39775. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39776. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39777. }
  39778. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39779. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39780. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39781. if (scene._mirroredCameraPosition) {
  39782. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39783. }
  39784. else {
  39785. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39786. }
  39787. }
  39788. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39789. var depth = 1.0;
  39790. if (!this._refractionTexture.isCube) {
  39791. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39792. if (this._refractionTexture.depth) {
  39793. depth = this._refractionTexture.depth;
  39794. }
  39795. }
  39796. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39797. }
  39798. }
  39799. // Point size
  39800. if (this.pointsCloud) {
  39801. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39802. }
  39803. if (defines.SPECULARTERM) {
  39804. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39805. }
  39806. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39807. // Diffuse
  39808. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39809. }
  39810. // Textures
  39811. if (scene.texturesEnabled) {
  39812. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39813. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39814. }
  39815. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39816. effect.setTexture("ambientSampler", this._ambientTexture);
  39817. }
  39818. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39819. effect.setTexture("opacitySampler", this._opacityTexture);
  39820. }
  39821. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39822. if (this._reflectionTexture.isCube) {
  39823. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39824. }
  39825. else {
  39826. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39827. }
  39828. }
  39829. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39830. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39831. }
  39832. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39833. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39834. }
  39835. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39836. effect.setTexture("specularSampler", this._specularTexture);
  39837. }
  39838. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39839. effect.setTexture("bumpSampler", this._bumpTexture);
  39840. }
  39841. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39842. var depth = 1.0;
  39843. if (this._refractionTexture.isCube) {
  39844. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39845. }
  39846. else {
  39847. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39848. }
  39849. }
  39850. }
  39851. // Clip plane
  39852. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39853. // Colors
  39854. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39855. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39856. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39857. }
  39858. if (mustRebind || !this.isFrozen) {
  39859. // Lights
  39860. if (scene.lightsEnabled && !this._disableLighting) {
  39861. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39862. }
  39863. // View
  39864. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39865. this.bindView(effect);
  39866. }
  39867. // Fog
  39868. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39869. // Morph targets
  39870. if (defines.NUM_MORPH_INFLUENCERS) {
  39871. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39872. }
  39873. // Log. depth
  39874. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39875. // image processing
  39876. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39877. this._imageProcessingConfiguration.bind(this._activeEffect);
  39878. }
  39879. }
  39880. this._uniformBuffer.update();
  39881. this._afterBind(mesh, this._activeEffect);
  39882. };
  39883. StandardMaterial.prototype.getAnimatables = function () {
  39884. var results = [];
  39885. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39886. results.push(this._diffuseTexture);
  39887. }
  39888. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39889. results.push(this._ambientTexture);
  39890. }
  39891. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39892. results.push(this._opacityTexture);
  39893. }
  39894. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39895. results.push(this._reflectionTexture);
  39896. }
  39897. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39898. results.push(this._emissiveTexture);
  39899. }
  39900. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39901. results.push(this._specularTexture);
  39902. }
  39903. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39904. results.push(this._bumpTexture);
  39905. }
  39906. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39907. results.push(this._lightmapTexture);
  39908. }
  39909. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39910. results.push(this._refractionTexture);
  39911. }
  39912. return results;
  39913. };
  39914. StandardMaterial.prototype.getActiveTextures = function () {
  39915. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39916. if (this._diffuseTexture) {
  39917. activeTextures.push(this._diffuseTexture);
  39918. }
  39919. if (this._ambientTexture) {
  39920. activeTextures.push(this._ambientTexture);
  39921. }
  39922. if (this._opacityTexture) {
  39923. activeTextures.push(this._opacityTexture);
  39924. }
  39925. if (this._reflectionTexture) {
  39926. activeTextures.push(this._reflectionTexture);
  39927. }
  39928. if (this._emissiveTexture) {
  39929. activeTextures.push(this._emissiveTexture);
  39930. }
  39931. if (this._specularTexture) {
  39932. activeTextures.push(this._specularTexture);
  39933. }
  39934. if (this._bumpTexture) {
  39935. activeTextures.push(this._bumpTexture);
  39936. }
  39937. if (this._lightmapTexture) {
  39938. activeTextures.push(this._lightmapTexture);
  39939. }
  39940. if (this._refractionTexture) {
  39941. activeTextures.push(this._refractionTexture);
  39942. }
  39943. return activeTextures;
  39944. };
  39945. StandardMaterial.prototype.hasTexture = function (texture) {
  39946. if (_super.prototype.hasTexture.call(this, texture)) {
  39947. return true;
  39948. }
  39949. if (this._diffuseTexture === texture) {
  39950. return true;
  39951. }
  39952. if (this._ambientTexture === texture) {
  39953. return true;
  39954. }
  39955. if (this._opacityTexture === texture) {
  39956. return true;
  39957. }
  39958. if (this._reflectionTexture === texture) {
  39959. return true;
  39960. }
  39961. if (this._emissiveTexture === texture) {
  39962. return true;
  39963. }
  39964. if (this._specularTexture === texture) {
  39965. return true;
  39966. }
  39967. if (this._bumpTexture === texture) {
  39968. return true;
  39969. }
  39970. if (this._lightmapTexture === texture) {
  39971. return true;
  39972. }
  39973. if (this._refractionTexture === texture) {
  39974. return true;
  39975. }
  39976. return false;
  39977. };
  39978. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39979. if (forceDisposeTextures) {
  39980. if (this._diffuseTexture) {
  39981. this._diffuseTexture.dispose();
  39982. }
  39983. if (this._ambientTexture) {
  39984. this._ambientTexture.dispose();
  39985. }
  39986. if (this._opacityTexture) {
  39987. this._opacityTexture.dispose();
  39988. }
  39989. if (this._reflectionTexture) {
  39990. this._reflectionTexture.dispose();
  39991. }
  39992. if (this._emissiveTexture) {
  39993. this._emissiveTexture.dispose();
  39994. }
  39995. if (this._specularTexture) {
  39996. this._specularTexture.dispose();
  39997. }
  39998. if (this._bumpTexture) {
  39999. this._bumpTexture.dispose();
  40000. }
  40001. if (this._lightmapTexture) {
  40002. this._lightmapTexture.dispose();
  40003. }
  40004. if (this._refractionTexture) {
  40005. this._refractionTexture.dispose();
  40006. }
  40007. }
  40008. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40009. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40010. }
  40011. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40012. };
  40013. StandardMaterial.prototype.clone = function (name) {
  40014. var _this = this;
  40015. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40016. result.name = name;
  40017. result.id = name;
  40018. return result;
  40019. };
  40020. StandardMaterial.prototype.serialize = function () {
  40021. return BABYLON.SerializationHelper.Serialize(this);
  40022. };
  40023. // Statics
  40024. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40025. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40026. };
  40027. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40028. get: function () {
  40029. return StandardMaterial._DiffuseTextureEnabled;
  40030. },
  40031. set: function (value) {
  40032. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40033. return;
  40034. }
  40035. StandardMaterial._DiffuseTextureEnabled = value;
  40036. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40037. },
  40038. enumerable: true,
  40039. configurable: true
  40040. });
  40041. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40042. get: function () {
  40043. return StandardMaterial._AmbientTextureEnabled;
  40044. },
  40045. set: function (value) {
  40046. if (StandardMaterial._AmbientTextureEnabled === value) {
  40047. return;
  40048. }
  40049. StandardMaterial._AmbientTextureEnabled = value;
  40050. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40051. },
  40052. enumerable: true,
  40053. configurable: true
  40054. });
  40055. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40056. get: function () {
  40057. return StandardMaterial._OpacityTextureEnabled;
  40058. },
  40059. set: function (value) {
  40060. if (StandardMaterial._OpacityTextureEnabled === value) {
  40061. return;
  40062. }
  40063. StandardMaterial._OpacityTextureEnabled = value;
  40064. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40065. },
  40066. enumerable: true,
  40067. configurable: true
  40068. });
  40069. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40070. get: function () {
  40071. return StandardMaterial._ReflectionTextureEnabled;
  40072. },
  40073. set: function (value) {
  40074. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40075. return;
  40076. }
  40077. StandardMaterial._ReflectionTextureEnabled = value;
  40078. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40079. },
  40080. enumerable: true,
  40081. configurable: true
  40082. });
  40083. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40084. get: function () {
  40085. return StandardMaterial._EmissiveTextureEnabled;
  40086. },
  40087. set: function (value) {
  40088. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40089. return;
  40090. }
  40091. StandardMaterial._EmissiveTextureEnabled = value;
  40092. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40093. },
  40094. enumerable: true,
  40095. configurable: true
  40096. });
  40097. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40098. get: function () {
  40099. return StandardMaterial._SpecularTextureEnabled;
  40100. },
  40101. set: function (value) {
  40102. if (StandardMaterial._SpecularTextureEnabled === value) {
  40103. return;
  40104. }
  40105. StandardMaterial._SpecularTextureEnabled = value;
  40106. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40107. },
  40108. enumerable: true,
  40109. configurable: true
  40110. });
  40111. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40112. get: function () {
  40113. return StandardMaterial._BumpTextureEnabled;
  40114. },
  40115. set: function (value) {
  40116. if (StandardMaterial._BumpTextureEnabled === value) {
  40117. return;
  40118. }
  40119. StandardMaterial._BumpTextureEnabled = value;
  40120. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40121. },
  40122. enumerable: true,
  40123. configurable: true
  40124. });
  40125. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40126. get: function () {
  40127. return StandardMaterial._LightmapTextureEnabled;
  40128. },
  40129. set: function (value) {
  40130. if (StandardMaterial._LightmapTextureEnabled === value) {
  40131. return;
  40132. }
  40133. StandardMaterial._LightmapTextureEnabled = value;
  40134. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40135. },
  40136. enumerable: true,
  40137. configurable: true
  40138. });
  40139. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40140. get: function () {
  40141. return StandardMaterial._RefractionTextureEnabled;
  40142. },
  40143. set: function (value) {
  40144. if (StandardMaterial._RefractionTextureEnabled === value) {
  40145. return;
  40146. }
  40147. StandardMaterial._RefractionTextureEnabled = value;
  40148. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40149. },
  40150. enumerable: true,
  40151. configurable: true
  40152. });
  40153. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40154. get: function () {
  40155. return StandardMaterial._ColorGradingTextureEnabled;
  40156. },
  40157. set: function (value) {
  40158. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40159. return;
  40160. }
  40161. StandardMaterial._ColorGradingTextureEnabled = value;
  40162. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40163. },
  40164. enumerable: true,
  40165. configurable: true
  40166. });
  40167. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40168. get: function () {
  40169. return StandardMaterial._FresnelEnabled;
  40170. },
  40171. set: function (value) {
  40172. if (StandardMaterial._FresnelEnabled === value) {
  40173. return;
  40174. }
  40175. StandardMaterial._FresnelEnabled = value;
  40176. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40177. },
  40178. enumerable: true,
  40179. configurable: true
  40180. });
  40181. // Flags used to enable or disable a type of texture for all Standard Materials
  40182. StandardMaterial._DiffuseTextureEnabled = true;
  40183. StandardMaterial._AmbientTextureEnabled = true;
  40184. StandardMaterial._OpacityTextureEnabled = true;
  40185. StandardMaterial._ReflectionTextureEnabled = true;
  40186. StandardMaterial._EmissiveTextureEnabled = true;
  40187. StandardMaterial._SpecularTextureEnabled = true;
  40188. StandardMaterial._BumpTextureEnabled = true;
  40189. StandardMaterial._LightmapTextureEnabled = true;
  40190. StandardMaterial._RefractionTextureEnabled = true;
  40191. StandardMaterial._ColorGradingTextureEnabled = true;
  40192. StandardMaterial._FresnelEnabled = true;
  40193. __decorate([
  40194. BABYLON.serializeAsTexture("diffuseTexture")
  40195. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40196. __decorate([
  40197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40198. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40199. __decorate([
  40200. BABYLON.serializeAsTexture("ambientTexture")
  40201. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40202. __decorate([
  40203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40204. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40205. __decorate([
  40206. BABYLON.serializeAsTexture("opacityTexture")
  40207. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40208. __decorate([
  40209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40210. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40211. __decorate([
  40212. BABYLON.serializeAsTexture("reflectionTexture")
  40213. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40214. __decorate([
  40215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40216. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40217. __decorate([
  40218. BABYLON.serializeAsTexture("emissiveTexture")
  40219. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40220. __decorate([
  40221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40222. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40223. __decorate([
  40224. BABYLON.serializeAsTexture("specularTexture")
  40225. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40226. __decorate([
  40227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40228. ], StandardMaterial.prototype, "specularTexture", void 0);
  40229. __decorate([
  40230. BABYLON.serializeAsTexture("bumpTexture")
  40231. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40232. __decorate([
  40233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40234. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40235. __decorate([
  40236. BABYLON.serializeAsTexture("lightmapTexture")
  40237. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40238. __decorate([
  40239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40240. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40241. __decorate([
  40242. BABYLON.serializeAsTexture("refractionTexture")
  40243. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40244. __decorate([
  40245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40246. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40247. __decorate([
  40248. BABYLON.serializeAsColor3("ambient")
  40249. ], StandardMaterial.prototype, "ambientColor", void 0);
  40250. __decorate([
  40251. BABYLON.serializeAsColor3("diffuse")
  40252. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40253. __decorate([
  40254. BABYLON.serializeAsColor3("specular")
  40255. ], StandardMaterial.prototype, "specularColor", void 0);
  40256. __decorate([
  40257. BABYLON.serializeAsColor3("emissive")
  40258. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40259. __decorate([
  40260. BABYLON.serialize()
  40261. ], StandardMaterial.prototype, "specularPower", void 0);
  40262. __decorate([
  40263. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40264. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40265. __decorate([
  40266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40267. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40268. __decorate([
  40269. BABYLON.serialize("useEmissiveAsIllumination")
  40270. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40271. __decorate([
  40272. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40273. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40274. __decorate([
  40275. BABYLON.serialize("linkEmissiveWithDiffuse")
  40276. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40277. __decorate([
  40278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40279. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40280. __decorate([
  40281. BABYLON.serialize("useSpecularOverAlpha")
  40282. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40283. __decorate([
  40284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40285. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40286. __decorate([
  40287. BABYLON.serialize("useReflectionOverAlpha")
  40288. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40289. __decorate([
  40290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40291. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40292. __decorate([
  40293. BABYLON.serialize("disableLighting")
  40294. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40295. __decorate([
  40296. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40297. ], StandardMaterial.prototype, "disableLighting", void 0);
  40298. __decorate([
  40299. BABYLON.serialize("useObjectSpaceNormalMap")
  40300. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40301. __decorate([
  40302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40303. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40304. __decorate([
  40305. BABYLON.serialize("useParallax")
  40306. ], StandardMaterial.prototype, "_useParallax", void 0);
  40307. __decorate([
  40308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40309. ], StandardMaterial.prototype, "useParallax", void 0);
  40310. __decorate([
  40311. BABYLON.serialize("useParallaxOcclusion")
  40312. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40313. __decorate([
  40314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40315. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40316. __decorate([
  40317. BABYLON.serialize()
  40318. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40319. __decorate([
  40320. BABYLON.serialize("roughness")
  40321. ], StandardMaterial.prototype, "_roughness", void 0);
  40322. __decorate([
  40323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40324. ], StandardMaterial.prototype, "roughness", void 0);
  40325. __decorate([
  40326. BABYLON.serialize()
  40327. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40328. __decorate([
  40329. BABYLON.serialize()
  40330. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40331. __decorate([
  40332. BABYLON.serialize("useLightmapAsShadowmap")
  40333. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40334. __decorate([
  40335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40336. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40337. __decorate([
  40338. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40339. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40340. __decorate([
  40341. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40342. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40343. __decorate([
  40344. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40345. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40346. __decorate([
  40347. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40348. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40349. __decorate([
  40350. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40351. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40352. __decorate([
  40353. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40354. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40355. __decorate([
  40356. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40357. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40358. __decorate([
  40359. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40360. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40361. __decorate([
  40362. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40363. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40364. __decorate([
  40365. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40366. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40367. __decorate([
  40368. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40369. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40370. __decorate([
  40371. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40372. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40373. __decorate([
  40374. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40375. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40376. __decorate([
  40377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40378. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40379. __decorate([
  40380. BABYLON.serialize("maxSimultaneousLights")
  40381. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40382. __decorate([
  40383. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40384. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40385. __decorate([
  40386. BABYLON.serialize("invertNormalMapX")
  40387. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40388. __decorate([
  40389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40390. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40391. __decorate([
  40392. BABYLON.serialize("invertNormalMapY")
  40393. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40394. __decorate([
  40395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40396. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40397. __decorate([
  40398. BABYLON.serialize("twoSidedLighting")
  40399. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40400. __decorate([
  40401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40402. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40403. __decorate([
  40404. BABYLON.serialize()
  40405. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40406. return StandardMaterial;
  40407. }(BABYLON.PushMaterial));
  40408. BABYLON.StandardMaterial = StandardMaterial;
  40409. })(BABYLON || (BABYLON = {}));
  40410. //# sourceMappingURL=babylon.standardMaterial.js.map
  40411. var BABYLON;
  40412. (function (BABYLON) {
  40413. /**
  40414. * Manages the defines for the PBR Material.
  40415. */
  40416. var PBRMaterialDefines = /** @class */ (function (_super) {
  40417. __extends(PBRMaterialDefines, _super);
  40418. /**
  40419. * Initializes the PBR Material defines.
  40420. */
  40421. function PBRMaterialDefines() {
  40422. var _this = _super.call(this) || this;
  40423. _this.PBR = true;
  40424. _this.MAINUV1 = false;
  40425. _this.MAINUV2 = false;
  40426. _this.UV1 = false;
  40427. _this.UV2 = false;
  40428. _this.ALBEDO = false;
  40429. _this.ALBEDODIRECTUV = 0;
  40430. _this.VERTEXCOLOR = false;
  40431. _this.AMBIENT = false;
  40432. _this.AMBIENTDIRECTUV = 0;
  40433. _this.AMBIENTINGRAYSCALE = false;
  40434. _this.OPACITY = false;
  40435. _this.VERTEXALPHA = false;
  40436. _this.OPACITYDIRECTUV = 0;
  40437. _this.OPACITYRGB = false;
  40438. _this.ALPHATEST = false;
  40439. _this.DEPTHPREPASS = false;
  40440. _this.ALPHABLEND = false;
  40441. _this.ALPHAFROMALBEDO = false;
  40442. _this.ALPHATESTVALUE = 0.5;
  40443. _this.SPECULAROVERALPHA = false;
  40444. _this.RADIANCEOVERALPHA = false;
  40445. _this.ALPHAFRESNEL = false;
  40446. _this.LINEARALPHAFRESNEL = false;
  40447. _this.PREMULTIPLYALPHA = false;
  40448. _this.EMISSIVE = false;
  40449. _this.EMISSIVEDIRECTUV = 0;
  40450. _this.REFLECTIVITY = false;
  40451. _this.REFLECTIVITYDIRECTUV = 0;
  40452. _this.SPECULARTERM = false;
  40453. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40454. _this.MICROSURFACEAUTOMATIC = false;
  40455. _this.LODBASEDMICROSFURACE = false;
  40456. _this.MICROSURFACEMAP = false;
  40457. _this.MICROSURFACEMAPDIRECTUV = 0;
  40458. _this.METALLICWORKFLOW = false;
  40459. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40460. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40461. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40462. _this.AOSTOREINMETALMAPRED = false;
  40463. _this.ENVIRONMENTBRDF = false;
  40464. _this.NORMAL = false;
  40465. _this.TANGENT = false;
  40466. _this.BUMP = false;
  40467. _this.BUMPDIRECTUV = 0;
  40468. _this.OBJECTSPACE_NORMALMAP = false;
  40469. _this.PARALLAX = false;
  40470. _this.PARALLAXOCCLUSION = false;
  40471. _this.NORMALXYSCALE = true;
  40472. _this.LIGHTMAP = false;
  40473. _this.LIGHTMAPDIRECTUV = 0;
  40474. _this.USELIGHTMAPASSHADOWMAP = false;
  40475. _this.REFLECTION = false;
  40476. _this.REFLECTIONMAP_3D = false;
  40477. _this.REFLECTIONMAP_SPHERICAL = false;
  40478. _this.REFLECTIONMAP_PLANAR = false;
  40479. _this.REFLECTIONMAP_CUBIC = false;
  40480. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40481. _this.REFLECTIONMAP_PROJECTION = false;
  40482. _this.REFLECTIONMAP_SKYBOX = false;
  40483. _this.REFLECTIONMAP_EXPLICIT = false;
  40484. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40485. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40486. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40487. _this.INVERTCUBICMAP = false;
  40488. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40489. _this.USESPHERICALINVERTEX = false;
  40490. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40491. _this.LODINREFLECTIONALPHA = false;
  40492. _this.GAMMAREFLECTION = false;
  40493. _this.RADIANCEOCCLUSION = false;
  40494. _this.HORIZONOCCLUSION = false;
  40495. _this.REFRACTION = false;
  40496. _this.REFRACTIONMAP_3D = false;
  40497. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40498. _this.LODINREFRACTIONALPHA = false;
  40499. _this.GAMMAREFRACTION = false;
  40500. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40501. _this.INSTANCES = false;
  40502. _this.NUM_BONE_INFLUENCERS = 0;
  40503. _this.BonesPerMesh = 0;
  40504. _this.NONUNIFORMSCALING = false;
  40505. _this.MORPHTARGETS = false;
  40506. _this.MORPHTARGETS_NORMAL = false;
  40507. _this.MORPHTARGETS_TANGENT = false;
  40508. _this.NUM_MORPH_INFLUENCERS = 0;
  40509. _this.IMAGEPROCESSING = false;
  40510. _this.VIGNETTE = false;
  40511. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40512. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40513. _this.TONEMAPPING = false;
  40514. _this.CONTRAST = false;
  40515. _this.COLORCURVES = false;
  40516. _this.COLORGRADING = false;
  40517. _this.COLORGRADING3D = false;
  40518. _this.SAMPLER3DGREENDEPTH = false;
  40519. _this.SAMPLER3DBGRMAP = false;
  40520. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40521. _this.EXPOSURE = false;
  40522. _this.GRAIN = false;
  40523. _this.USEPHYSICALLIGHTFALLOFF = false;
  40524. _this.TWOSIDEDLIGHTING = false;
  40525. _this.SHADOWFLOAT = false;
  40526. _this.CLIPPLANE = false;
  40527. _this.POINTSIZE = false;
  40528. _this.FOG = false;
  40529. _this.LOGARITHMICDEPTH = false;
  40530. _this.FORCENORMALFORWARD = false;
  40531. _this.rebuild();
  40532. return _this;
  40533. }
  40534. /**
  40535. * Resets the PBR Material defines.
  40536. */
  40537. PBRMaterialDefines.prototype.reset = function () {
  40538. _super.prototype.reset.call(this);
  40539. this.ALPHATESTVALUE = 0.5;
  40540. this.PBR = true;
  40541. };
  40542. return PBRMaterialDefines;
  40543. }(BABYLON.MaterialDefines));
  40544. /**
  40545. * The Physically based material base class of BJS.
  40546. *
  40547. * This offers the main features of a standard PBR material.
  40548. * For more information, please refer to the documentation :
  40549. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40550. */
  40551. var PBRBaseMaterial = /** @class */ (function (_super) {
  40552. __extends(PBRBaseMaterial, _super);
  40553. /**
  40554. * Instantiates a new PBRMaterial instance.
  40555. *
  40556. * @param name The material name
  40557. * @param scene The scene the material will be use in.
  40558. */
  40559. function PBRBaseMaterial(name, scene) {
  40560. var _this = _super.call(this, name, scene) || this;
  40561. /**
  40562. * Intensity of the direct lights e.g. the four lights available in your scene.
  40563. * This impacts both the direct diffuse and specular highlights.
  40564. */
  40565. _this._directIntensity = 1.0;
  40566. /**
  40567. * Intensity of the emissive part of the material.
  40568. * This helps controlling the emissive effect without modifying the emissive color.
  40569. */
  40570. _this._emissiveIntensity = 1.0;
  40571. /**
  40572. * Intensity of the environment e.g. how much the environment will light the object
  40573. * either through harmonics for rough material or through the refelction for shiny ones.
  40574. */
  40575. _this._environmentIntensity = 1.0;
  40576. /**
  40577. * This is a special control allowing the reduction of the specular highlights coming from the
  40578. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40579. */
  40580. _this._specularIntensity = 1.0;
  40581. /**
  40582. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40583. */
  40584. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40585. /**
  40586. * Debug Control allowing disabling the bump map on this material.
  40587. */
  40588. _this._disableBumpMap = false;
  40589. /**
  40590. * AKA Occlusion Texture Intensity in other nomenclature.
  40591. */
  40592. _this._ambientTextureStrength = 1.0;
  40593. /**
  40594. * The color of a material in ambient lighting.
  40595. */
  40596. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40597. /**
  40598. * AKA Diffuse Color in other nomenclature.
  40599. */
  40600. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40601. /**
  40602. * AKA Specular Color in other nomenclature.
  40603. */
  40604. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40605. /**
  40606. * The color applied when light is reflected from a material.
  40607. */
  40608. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40609. /**
  40610. * The color applied when light is emitted from a material.
  40611. */
  40612. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40613. /**
  40614. * AKA Glossiness in other nomenclature.
  40615. */
  40616. _this._microSurface = 0.9;
  40617. /**
  40618. * source material index of refraction (IOR)' / 'destination material IOR.
  40619. */
  40620. _this._indexOfRefraction = 0.66;
  40621. /**
  40622. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40623. */
  40624. _this._invertRefractionY = false;
  40625. /**
  40626. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40627. * Materials half opaque for instance using refraction could benefit from this control.
  40628. */
  40629. _this._linkRefractionWithTransparency = false;
  40630. /**
  40631. * Specifies that the material will use the light map as a show map.
  40632. */
  40633. _this._useLightmapAsShadowmap = false;
  40634. /**
  40635. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40636. * makes the reflect vector face the model (under horizon).
  40637. */
  40638. _this._useHorizonOcclusion = true;
  40639. /**
  40640. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40641. * too much the area relying on ambient texture to define their ambient occlusion.
  40642. */
  40643. _this._useRadianceOcclusion = true;
  40644. /**
  40645. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40646. */
  40647. _this._useAlphaFromAlbedoTexture = false;
  40648. /**
  40649. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40650. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40651. */
  40652. _this._useSpecularOverAlpha = true;
  40653. /**
  40654. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40655. */
  40656. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40657. /**
  40658. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40659. */
  40660. _this._useRoughnessFromMetallicTextureAlpha = true;
  40661. /**
  40662. * Specifies if the metallic texture contains the roughness information in its green channel.
  40663. */
  40664. _this._useRoughnessFromMetallicTextureGreen = false;
  40665. /**
  40666. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40667. */
  40668. _this._useMetallnessFromMetallicTextureBlue = false;
  40669. /**
  40670. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40671. */
  40672. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40673. /**
  40674. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40675. */
  40676. _this._useAmbientInGrayScale = false;
  40677. /**
  40678. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40679. * The material will try to infer what glossiness each pixel should be.
  40680. */
  40681. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40682. /**
  40683. * BJS is using an harcoded light falloff based on a manually sets up range.
  40684. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40685. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40686. */
  40687. _this._usePhysicalLightFalloff = true;
  40688. /**
  40689. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40690. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40691. */
  40692. _this._useRadianceOverAlpha = true;
  40693. /**
  40694. * Allows using an object space normal map (instead of tangent space).
  40695. */
  40696. _this._useObjectSpaceNormalMap = false;
  40697. /**
  40698. * Allows using the bump map in parallax mode.
  40699. */
  40700. _this._useParallax = false;
  40701. /**
  40702. * Allows using the bump map in parallax occlusion mode.
  40703. */
  40704. _this._useParallaxOcclusion = false;
  40705. /**
  40706. * Controls the scale bias of the parallax mode.
  40707. */
  40708. _this._parallaxScaleBias = 0.05;
  40709. /**
  40710. * If sets to true, disables all the lights affecting the material.
  40711. */
  40712. _this._disableLighting = false;
  40713. /**
  40714. * Number of Simultaneous lights allowed on the material.
  40715. */
  40716. _this._maxSimultaneousLights = 4;
  40717. /**
  40718. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40719. */
  40720. _this._invertNormalMapX = false;
  40721. /**
  40722. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40723. */
  40724. _this._invertNormalMapY = false;
  40725. /**
  40726. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40727. */
  40728. _this._twoSidedLighting = false;
  40729. /**
  40730. * Defines the alpha limits in alpha test mode.
  40731. */
  40732. _this._alphaCutOff = 0.4;
  40733. /**
  40734. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40735. */
  40736. _this._forceAlphaTest = false;
  40737. /**
  40738. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40739. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40740. */
  40741. _this._useAlphaFresnel = false;
  40742. /**
  40743. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40744. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40745. */
  40746. _this._useLinearAlphaFresnel = false;
  40747. /**
  40748. * The transparency mode of the material.
  40749. */
  40750. _this._transparencyMode = null;
  40751. /**
  40752. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40753. * from cos thetav and roughness:
  40754. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40755. */
  40756. _this._environmentBRDFTexture = null;
  40757. /**
  40758. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40759. */
  40760. _this._forceIrradianceInFragment = false;
  40761. /**
  40762. * Force normal to face away from face.
  40763. */
  40764. _this._forceNormalForward = false;
  40765. /**
  40766. * Stores the available render targets.
  40767. */
  40768. _this._renderTargets = new BABYLON.SmartArray(16);
  40769. /**
  40770. * Sets the global ambient color for the material used in lighting calculations.
  40771. */
  40772. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40773. // Setup the default processing configuration to the scene.
  40774. _this._attachImageProcessingConfiguration(null);
  40775. _this.getRenderTargetTextures = function () {
  40776. _this._renderTargets.reset();
  40777. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40778. _this._renderTargets.push(_this._reflectionTexture);
  40779. }
  40780. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40781. _this._renderTargets.push(_this._refractionTexture);
  40782. }
  40783. return _this._renderTargets;
  40784. };
  40785. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40786. return _this;
  40787. }
  40788. /**
  40789. * Attaches a new image processing configuration to the PBR Material.
  40790. * @param configuration
  40791. */
  40792. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40793. var _this = this;
  40794. if (configuration === this._imageProcessingConfiguration) {
  40795. return;
  40796. }
  40797. // Detaches observer.
  40798. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40799. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40800. }
  40801. // Pick the scene configuration if needed.
  40802. if (!configuration) {
  40803. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40804. }
  40805. else {
  40806. this._imageProcessingConfiguration = configuration;
  40807. }
  40808. // Attaches observer.
  40809. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40810. _this._markAllSubMeshesAsImageProcessingDirty();
  40811. });
  40812. };
  40813. /**
  40814. * Gets the name of the material class.
  40815. */
  40816. PBRBaseMaterial.prototype.getClassName = function () {
  40817. return "PBRBaseMaterial";
  40818. };
  40819. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40820. /**
  40821. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40822. */
  40823. get: function () {
  40824. return this._useLogarithmicDepth;
  40825. },
  40826. /**
  40827. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40828. */
  40829. set: function (value) {
  40830. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40831. },
  40832. enumerable: true,
  40833. configurable: true
  40834. });
  40835. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40836. /**
  40837. * Gets the current transparency mode.
  40838. */
  40839. get: function () {
  40840. return this._transparencyMode;
  40841. },
  40842. /**
  40843. * Sets the transparency mode of the material.
  40844. */
  40845. set: function (value) {
  40846. if (this._transparencyMode === value) {
  40847. return;
  40848. }
  40849. this._transparencyMode = value;
  40850. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40851. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40852. },
  40853. enumerable: true,
  40854. configurable: true
  40855. });
  40856. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40857. /**
  40858. * Returns true if alpha blending should be disabled.
  40859. */
  40860. get: function () {
  40861. return (this._linkRefractionWithTransparency ||
  40862. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40863. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40864. },
  40865. enumerable: true,
  40866. configurable: true
  40867. });
  40868. /**
  40869. * Specifies whether or not this material should be rendered in alpha blend mode.
  40870. */
  40871. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40872. if (this._disableAlphaBlending) {
  40873. return false;
  40874. }
  40875. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40876. };
  40877. /**
  40878. * Specifies if the mesh will require alpha blending.
  40879. * @param mesh - BJS mesh.
  40880. */
  40881. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40882. if (this._disableAlphaBlending) {
  40883. return false;
  40884. }
  40885. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40886. };
  40887. /**
  40888. * Specifies whether or not this material should be rendered in alpha test mode.
  40889. */
  40890. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40891. if (this._forceAlphaTest) {
  40892. return true;
  40893. }
  40894. if (this._linkRefractionWithTransparency) {
  40895. return false;
  40896. }
  40897. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40898. };
  40899. /**
  40900. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40901. */
  40902. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40903. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40904. };
  40905. /**
  40906. * Gets the texture used for the alpha test.
  40907. */
  40908. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40909. return this._albedoTexture;
  40910. };
  40911. /**
  40912. * Specifies that the submesh is ready to be used.
  40913. * @param mesh - BJS mesh.
  40914. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40915. * @param useInstances - Specifies that instances should be used.
  40916. * @returns - boolean indicating that the submesh is ready or not.
  40917. */
  40918. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40919. if (subMesh.effect && this.isFrozen) {
  40920. if (this._wasPreviouslyReady) {
  40921. return true;
  40922. }
  40923. }
  40924. if (!subMesh._materialDefines) {
  40925. subMesh._materialDefines = new PBRMaterialDefines();
  40926. }
  40927. var defines = subMesh._materialDefines;
  40928. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40929. if (defines._renderId === this.getScene().getRenderId()) {
  40930. return true;
  40931. }
  40932. }
  40933. var scene = this.getScene();
  40934. var engine = scene.getEngine();
  40935. if (defines._areTexturesDirty) {
  40936. if (scene.texturesEnabled) {
  40937. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40938. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40939. return false;
  40940. }
  40941. }
  40942. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40943. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40944. return false;
  40945. }
  40946. }
  40947. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40948. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40949. return false;
  40950. }
  40951. }
  40952. var reflectionTexture = this._getReflectionTexture();
  40953. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40954. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40955. return false;
  40956. }
  40957. }
  40958. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40959. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40960. return false;
  40961. }
  40962. }
  40963. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40964. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40965. return false;
  40966. }
  40967. }
  40968. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40969. if (this._metallicTexture) {
  40970. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40971. return false;
  40972. }
  40973. }
  40974. else if (this._reflectivityTexture) {
  40975. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40976. return false;
  40977. }
  40978. }
  40979. if (this._microSurfaceTexture) {
  40980. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40981. return false;
  40982. }
  40983. }
  40984. }
  40985. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40986. // Bump texture cannot be not blocking.
  40987. if (!this._bumpTexture.isReady()) {
  40988. return false;
  40989. }
  40990. }
  40991. var refractionTexture = this._getRefractionTexture();
  40992. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40993. if (!refractionTexture.isReadyOrNotBlocking()) {
  40994. return false;
  40995. }
  40996. }
  40997. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40998. // This is blocking.
  40999. if (!this._environmentBRDFTexture.isReady()) {
  41000. return false;
  41001. }
  41002. }
  41003. }
  41004. }
  41005. if (defines._areImageProcessingDirty) {
  41006. if (!this._imageProcessingConfiguration.isReady()) {
  41007. return false;
  41008. }
  41009. }
  41010. if (!engine.getCaps().standardDerivatives) {
  41011. var bufferMesh = null;
  41012. if (mesh.getClassName() === "InstancedMesh") {
  41013. bufferMesh = mesh.sourceMesh;
  41014. }
  41015. else if (mesh.getClassName() === "Mesh") {
  41016. bufferMesh = mesh;
  41017. }
  41018. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41019. bufferMesh.createNormals(true);
  41020. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  41021. }
  41022. }
  41023. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41024. if (effect) {
  41025. scene.resetCachedMaterial();
  41026. subMesh.setEffect(effect, defines);
  41027. this.buildUniformLayout();
  41028. }
  41029. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41030. return false;
  41031. }
  41032. defines._renderId = scene.getRenderId();
  41033. this._wasPreviouslyReady = true;
  41034. return true;
  41035. };
  41036. /**
  41037. * Specifies if the material uses metallic roughness workflow.
  41038. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41039. */
  41040. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41041. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41042. return true;
  41043. }
  41044. return false;
  41045. };
  41046. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41047. if (onCompiled === void 0) { onCompiled = null; }
  41048. if (onError === void 0) { onError = null; }
  41049. if (useInstances === void 0) { useInstances = null; }
  41050. if (useClipPlane === void 0) { useClipPlane = null; }
  41051. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41052. if (!defines.isDirty) {
  41053. return null;
  41054. }
  41055. defines.markAsProcessed();
  41056. var scene = this.getScene();
  41057. var engine = scene.getEngine();
  41058. // Fallbacks
  41059. var fallbacks = new BABYLON.EffectFallbacks();
  41060. var fallbackRank = 0;
  41061. if (defines.USESPHERICALINVERTEX) {
  41062. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41063. }
  41064. if (defines.FOG) {
  41065. fallbacks.addFallback(fallbackRank, "FOG");
  41066. }
  41067. if (defines.POINTSIZE) {
  41068. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41069. }
  41070. if (defines.LOGARITHMICDEPTH) {
  41071. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41072. }
  41073. if (defines.PARALLAX) {
  41074. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41075. }
  41076. if (defines.PARALLAXOCCLUSION) {
  41077. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41078. }
  41079. if (defines.ENVIRONMENTBRDF) {
  41080. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41081. }
  41082. if (defines.TANGENT) {
  41083. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41084. }
  41085. if (defines.BUMP) {
  41086. fallbacks.addFallback(fallbackRank++, "BUMP");
  41087. }
  41088. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41089. if (defines.SPECULARTERM) {
  41090. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41091. }
  41092. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41093. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41094. }
  41095. if (defines.LIGHTMAP) {
  41096. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41097. }
  41098. if (defines.NORMAL) {
  41099. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41100. }
  41101. if (defines.AMBIENT) {
  41102. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41103. }
  41104. if (defines.EMISSIVE) {
  41105. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41106. }
  41107. if (defines.VERTEXCOLOR) {
  41108. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41109. }
  41110. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41111. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41112. }
  41113. if (defines.MORPHTARGETS) {
  41114. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41115. }
  41116. //Attributes
  41117. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41118. if (defines.NORMAL) {
  41119. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41120. }
  41121. if (defines.TANGENT) {
  41122. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41123. }
  41124. if (defines.UV1) {
  41125. attribs.push(BABYLON.VertexBuffer.UVKind);
  41126. }
  41127. if (defines.UV2) {
  41128. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41129. }
  41130. if (defines.VERTEXCOLOR) {
  41131. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41132. }
  41133. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41134. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41135. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41136. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41137. "vFogInfos", "vFogColor", "pointSize",
  41138. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41139. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41140. "mBones",
  41141. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41142. "vLightingIntensity",
  41143. "logarithmicDepthConstant",
  41144. "vSphericalX", "vSphericalY", "vSphericalZ",
  41145. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41146. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41147. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41148. "vTangentSpaceParams"
  41149. ];
  41150. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41151. "bumpSampler", "lightmapSampler", "opacitySampler",
  41152. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41153. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41154. "microSurfaceSampler", "environmentBrdfSampler"];
  41155. var uniformBuffers = ["Material", "Scene"];
  41156. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41157. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41158. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41159. uniformsNames: uniforms,
  41160. uniformBuffersNames: uniformBuffers,
  41161. samplers: samplers,
  41162. defines: defines,
  41163. maxSimultaneousLights: this._maxSimultaneousLights
  41164. });
  41165. var join = defines.toString();
  41166. return engine.createEffect("pbr", {
  41167. attributes: attribs,
  41168. uniformsNames: uniforms,
  41169. uniformBuffersNames: uniformBuffers,
  41170. samplers: samplers,
  41171. defines: join,
  41172. fallbacks: fallbacks,
  41173. onCompiled: onCompiled,
  41174. onError: onError,
  41175. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41176. }, engine);
  41177. };
  41178. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41179. if (useInstances === void 0) { useInstances = null; }
  41180. if (useClipPlane === void 0) { useClipPlane = null; }
  41181. var scene = this.getScene();
  41182. var engine = scene.getEngine();
  41183. // Lights
  41184. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41185. defines._needNormals = true;
  41186. // Textures
  41187. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41188. if (defines._areTexturesDirty) {
  41189. defines._needUVs = false;
  41190. if (scene.texturesEnabled) {
  41191. if (scene.getEngine().getCaps().textureLOD) {
  41192. defines.LODBASEDMICROSFURACE = true;
  41193. }
  41194. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41195. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41196. }
  41197. else {
  41198. defines.ALBEDO = false;
  41199. }
  41200. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41201. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41202. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41203. }
  41204. else {
  41205. defines.AMBIENT = false;
  41206. }
  41207. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41208. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41209. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41210. }
  41211. else {
  41212. defines.OPACITY = false;
  41213. }
  41214. var reflectionTexture = this._getReflectionTexture();
  41215. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41216. defines.REFLECTION = true;
  41217. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41218. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41219. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41220. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41221. defines.INVERTCUBICMAP = true;
  41222. }
  41223. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41224. switch (reflectionTexture.coordinatesMode) {
  41225. case BABYLON.Texture.CUBIC_MODE:
  41226. case BABYLON.Texture.INVCUBIC_MODE:
  41227. defines.REFLECTIONMAP_CUBIC = true;
  41228. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41229. break;
  41230. case BABYLON.Texture.EXPLICIT_MODE:
  41231. defines.REFLECTIONMAP_EXPLICIT = true;
  41232. break;
  41233. case BABYLON.Texture.PLANAR_MODE:
  41234. defines.REFLECTIONMAP_PLANAR = true;
  41235. break;
  41236. case BABYLON.Texture.PROJECTION_MODE:
  41237. defines.REFLECTIONMAP_PROJECTION = true;
  41238. break;
  41239. case BABYLON.Texture.SKYBOX_MODE:
  41240. defines.REFLECTIONMAP_SKYBOX = true;
  41241. break;
  41242. case BABYLON.Texture.SPHERICAL_MODE:
  41243. defines.REFLECTIONMAP_SPHERICAL = true;
  41244. break;
  41245. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41246. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41247. break;
  41248. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41249. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41250. break;
  41251. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41252. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41253. break;
  41254. }
  41255. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41256. if (reflectionTexture.sphericalPolynomial) {
  41257. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41258. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41259. defines.USESPHERICALINVERTEX = false;
  41260. }
  41261. else {
  41262. defines.USESPHERICALINVERTEX = true;
  41263. }
  41264. }
  41265. }
  41266. }
  41267. else {
  41268. defines.REFLECTION = false;
  41269. defines.REFLECTIONMAP_3D = false;
  41270. defines.REFLECTIONMAP_SPHERICAL = false;
  41271. defines.REFLECTIONMAP_PLANAR = false;
  41272. defines.REFLECTIONMAP_CUBIC = false;
  41273. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41274. defines.REFLECTIONMAP_PROJECTION = false;
  41275. defines.REFLECTIONMAP_SKYBOX = false;
  41276. defines.REFLECTIONMAP_EXPLICIT = false;
  41277. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41278. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41279. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41280. defines.INVERTCUBICMAP = false;
  41281. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41282. defines.USESPHERICALINVERTEX = false;
  41283. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41284. defines.LODINREFLECTIONALPHA = false;
  41285. defines.GAMMAREFLECTION = false;
  41286. }
  41287. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41288. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41289. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41290. }
  41291. else {
  41292. defines.LIGHTMAP = false;
  41293. }
  41294. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41295. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41296. }
  41297. else {
  41298. defines.EMISSIVE = false;
  41299. }
  41300. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41301. if (this._metallicTexture) {
  41302. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41303. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41304. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41305. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41306. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41307. }
  41308. else if (this._reflectivityTexture) {
  41309. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41310. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41311. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41312. }
  41313. else {
  41314. defines.REFLECTIVITY = false;
  41315. }
  41316. if (this._microSurfaceTexture) {
  41317. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41318. }
  41319. else {
  41320. defines.MICROSURFACEMAP = false;
  41321. }
  41322. }
  41323. else {
  41324. defines.REFLECTIVITY = false;
  41325. defines.MICROSURFACEMAP = false;
  41326. }
  41327. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41328. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41329. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41330. defines.PARALLAX = true;
  41331. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41332. }
  41333. else {
  41334. defines.PARALLAX = false;
  41335. }
  41336. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41337. }
  41338. else {
  41339. defines.BUMP = false;
  41340. }
  41341. var refractionTexture = this._getRefractionTexture();
  41342. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41343. defines.REFRACTION = true;
  41344. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41345. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41346. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41347. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41348. if (this._linkRefractionWithTransparency) {
  41349. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41350. }
  41351. }
  41352. else {
  41353. defines.REFRACTION = false;
  41354. }
  41355. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41356. defines.ENVIRONMENTBRDF = true;
  41357. }
  41358. else {
  41359. defines.ENVIRONMENTBRDF = false;
  41360. }
  41361. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41362. defines.ALPHAFROMALBEDO = true;
  41363. }
  41364. else {
  41365. defines.ALPHAFROMALBEDO = false;
  41366. }
  41367. }
  41368. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41369. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41370. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41371. if (!this.backFaceCulling && this._twoSidedLighting) {
  41372. defines.TWOSIDEDLIGHTING = true;
  41373. }
  41374. else {
  41375. defines.TWOSIDEDLIGHTING = false;
  41376. }
  41377. defines.ALPHATESTVALUE = this._alphaCutOff;
  41378. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41379. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41380. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41381. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41382. }
  41383. if (defines._areImageProcessingDirty) {
  41384. this._imageProcessingConfiguration.prepareDefines(defines);
  41385. }
  41386. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41387. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41388. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41389. // Misc.
  41390. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41391. // Values that need to be evaluated on every frame
  41392. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41393. // Attribs
  41394. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41395. };
  41396. /**
  41397. * Force shader compilation
  41398. */
  41399. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41400. var _this = this;
  41401. var localOptions = __assign({ clipPlane: false }, options);
  41402. var defines = new PBRMaterialDefines();
  41403. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41404. if (effect.isReady()) {
  41405. if (onCompiled) {
  41406. onCompiled(this);
  41407. }
  41408. }
  41409. else {
  41410. effect.onCompileObservable.add(function () {
  41411. if (onCompiled) {
  41412. onCompiled(_this);
  41413. }
  41414. });
  41415. }
  41416. };
  41417. /**
  41418. * Initializes the uniform buffer layout for the shader.
  41419. */
  41420. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41421. // Order is important !
  41422. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41423. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41424. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41425. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41426. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41427. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41428. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41429. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41430. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41431. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41432. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41433. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41434. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41435. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41436. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41437. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41438. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41439. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41440. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41441. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41442. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41443. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41444. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41445. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41446. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41447. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41448. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41449. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41450. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41451. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41452. this._uniformBuffer.addUniform("pointSize", 1);
  41453. this._uniformBuffer.create();
  41454. };
  41455. /**
  41456. * Unbinds the textures.
  41457. */
  41458. PBRBaseMaterial.prototype.unbind = function () {
  41459. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41460. this._uniformBuffer.setTexture("reflectionSampler", null);
  41461. }
  41462. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41463. this._uniformBuffer.setTexture("refractionSampler", null);
  41464. }
  41465. _super.prototype.unbind.call(this);
  41466. };
  41467. /**
  41468. * Binds the submesh data.
  41469. * @param world - The world matrix.
  41470. * @param mesh - The BJS mesh.
  41471. * @param subMesh - A submesh of the BJS mesh.
  41472. */
  41473. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41474. var scene = this.getScene();
  41475. var defines = subMesh._materialDefines;
  41476. if (!defines) {
  41477. return;
  41478. }
  41479. var effect = subMesh.effect;
  41480. if (!effect) {
  41481. return;
  41482. }
  41483. this._activeEffect = effect;
  41484. // Matrices
  41485. this.bindOnlyWorldMatrix(world);
  41486. // Normal Matrix
  41487. if (defines.OBJECTSPACE_NORMALMAP) {
  41488. world.toNormalMatrix(this._normalMatrix);
  41489. this.bindOnlyNormalMatrix(this._normalMatrix);
  41490. }
  41491. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41492. // Bones
  41493. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41494. var reflectionTexture = null;
  41495. if (mustRebind) {
  41496. this._uniformBuffer.bindToEffect(effect, "Material");
  41497. this.bindViewProjection(effect);
  41498. reflectionTexture = this._getReflectionTexture();
  41499. var refractionTexture = this._getRefractionTexture();
  41500. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41501. // Texture uniforms
  41502. if (scene.texturesEnabled) {
  41503. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41504. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41505. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41506. }
  41507. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41508. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41509. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41510. }
  41511. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41512. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41513. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41514. }
  41515. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41516. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41517. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41518. if (reflectionTexture.boundingBoxSize) {
  41519. var cubeTexture = reflectionTexture;
  41520. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41521. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41522. }
  41523. var polynomials = reflectionTexture.sphericalPolynomial;
  41524. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41525. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41526. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41527. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41528. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41529. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41530. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41531. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41532. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41533. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41534. }
  41535. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41536. }
  41537. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41538. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41539. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41540. }
  41541. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41542. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41543. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41544. }
  41545. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41546. if (this._metallicTexture) {
  41547. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41548. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41549. }
  41550. else if (this._reflectivityTexture) {
  41551. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41552. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41553. }
  41554. if (this._microSurfaceTexture) {
  41555. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41556. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41557. }
  41558. }
  41559. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41560. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41561. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41562. if (scene._mirroredCameraPosition) {
  41563. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41564. }
  41565. else {
  41566. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41567. }
  41568. }
  41569. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41570. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41571. var depth = 1.0;
  41572. if (!refractionTexture.isCube) {
  41573. if (refractionTexture.depth) {
  41574. depth = refractionTexture.depth;
  41575. }
  41576. }
  41577. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41578. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41579. }
  41580. }
  41581. // Point size
  41582. if (this.pointsCloud) {
  41583. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41584. }
  41585. // Colors
  41586. if (defines.METALLICWORKFLOW) {
  41587. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41588. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41589. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41590. }
  41591. else {
  41592. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41593. }
  41594. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41595. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41596. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41597. // Misc
  41598. this._lightingInfos.x = this._directIntensity;
  41599. this._lightingInfos.y = this._emissiveIntensity;
  41600. this._lightingInfos.z = this._environmentIntensity;
  41601. this._lightingInfos.w = this._specularIntensity;
  41602. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41603. }
  41604. // Textures
  41605. if (scene.texturesEnabled) {
  41606. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41607. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41608. }
  41609. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41610. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41611. }
  41612. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41613. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41614. }
  41615. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41616. if (defines.LODBASEDMICROSFURACE) {
  41617. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41618. }
  41619. else {
  41620. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41621. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41622. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41623. }
  41624. }
  41625. if (defines.ENVIRONMENTBRDF) {
  41626. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41627. }
  41628. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41629. if (defines.LODBASEDMICROSFURACE) {
  41630. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41631. }
  41632. else {
  41633. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41634. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41635. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41636. }
  41637. }
  41638. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41639. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41640. }
  41641. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41642. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41643. }
  41644. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41645. if (this._metallicTexture) {
  41646. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41647. }
  41648. else if (this._reflectivityTexture) {
  41649. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41650. }
  41651. if (this._microSurfaceTexture) {
  41652. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41653. }
  41654. }
  41655. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41656. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41657. }
  41658. }
  41659. // Clip plane
  41660. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41661. // Colors
  41662. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41663. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41664. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41665. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41666. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41667. }
  41668. if (mustRebind || !this.isFrozen) {
  41669. // Lights
  41670. if (scene.lightsEnabled && !this._disableLighting) {
  41671. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41672. }
  41673. // View
  41674. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41675. this.bindView(effect);
  41676. }
  41677. // Fog
  41678. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41679. // Morph targets
  41680. if (defines.NUM_MORPH_INFLUENCERS) {
  41681. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41682. }
  41683. // image processing
  41684. this._imageProcessingConfiguration.bind(this._activeEffect);
  41685. // Log. depth
  41686. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41687. }
  41688. this._uniformBuffer.update();
  41689. this._afterBind(mesh);
  41690. };
  41691. /**
  41692. * Returns the animatable textures.
  41693. * @returns - Array of animatable textures.
  41694. */
  41695. PBRBaseMaterial.prototype.getAnimatables = function () {
  41696. var results = [];
  41697. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41698. results.push(this._albedoTexture);
  41699. }
  41700. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41701. results.push(this._ambientTexture);
  41702. }
  41703. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41704. results.push(this._opacityTexture);
  41705. }
  41706. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41707. results.push(this._reflectionTexture);
  41708. }
  41709. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41710. results.push(this._emissiveTexture);
  41711. }
  41712. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41713. results.push(this._metallicTexture);
  41714. }
  41715. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41716. results.push(this._reflectivityTexture);
  41717. }
  41718. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41719. results.push(this._bumpTexture);
  41720. }
  41721. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41722. results.push(this._lightmapTexture);
  41723. }
  41724. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41725. results.push(this._refractionTexture);
  41726. }
  41727. return results;
  41728. };
  41729. /**
  41730. * Returns the texture used for reflections.
  41731. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41732. */
  41733. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41734. if (this._reflectionTexture) {
  41735. return this._reflectionTexture;
  41736. }
  41737. return this.getScene().environmentTexture;
  41738. };
  41739. /**
  41740. * Returns the texture used for refraction or null if none is used.
  41741. * @returns - Refection texture if present. If no refraction texture and refraction
  41742. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41743. */
  41744. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41745. if (this._refractionTexture) {
  41746. return this._refractionTexture;
  41747. }
  41748. if (this._linkRefractionWithTransparency) {
  41749. return this.getScene().environmentTexture;
  41750. }
  41751. return null;
  41752. };
  41753. /**
  41754. * Disposes the resources of the material.
  41755. * @param forceDisposeEffect - Forces the disposal of effects.
  41756. * @param forceDisposeTextures - Forces the disposal of all textures.
  41757. */
  41758. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41759. if (forceDisposeTextures) {
  41760. if (this._albedoTexture) {
  41761. this._albedoTexture.dispose();
  41762. }
  41763. if (this._ambientTexture) {
  41764. this._ambientTexture.dispose();
  41765. }
  41766. if (this._opacityTexture) {
  41767. this._opacityTexture.dispose();
  41768. }
  41769. if (this._reflectionTexture) {
  41770. this._reflectionTexture.dispose();
  41771. }
  41772. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41773. this._environmentBRDFTexture.dispose();
  41774. }
  41775. if (this._emissiveTexture) {
  41776. this._emissiveTexture.dispose();
  41777. }
  41778. if (this._metallicTexture) {
  41779. this._metallicTexture.dispose();
  41780. }
  41781. if (this._reflectivityTexture) {
  41782. this._reflectivityTexture.dispose();
  41783. }
  41784. if (this._bumpTexture) {
  41785. this._bumpTexture.dispose();
  41786. }
  41787. if (this._lightmapTexture) {
  41788. this._lightmapTexture.dispose();
  41789. }
  41790. if (this._refractionTexture) {
  41791. this._refractionTexture.dispose();
  41792. }
  41793. }
  41794. this._renderTargets.dispose();
  41795. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41796. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41797. }
  41798. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41799. };
  41800. /**
  41801. * Stores the reflectivity values based on metallic roughness workflow.
  41802. */
  41803. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41804. __decorate([
  41805. BABYLON.serializeAsImageProcessingConfiguration()
  41806. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41807. __decorate([
  41808. BABYLON.serialize()
  41809. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41810. __decorate([
  41811. BABYLON.serialize()
  41812. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41813. return PBRBaseMaterial;
  41814. }(BABYLON.PushMaterial));
  41815. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41816. })(BABYLON || (BABYLON = {}));
  41817. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41818. var BABYLON;
  41819. (function (BABYLON) {
  41820. /**
  41821. * The Physically based simple base material of BJS.
  41822. *
  41823. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41824. * It is used as the base class for both the specGloss and metalRough conventions.
  41825. */
  41826. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41827. __extends(PBRBaseSimpleMaterial, _super);
  41828. /**
  41829. * Instantiates a new PBRMaterial instance.
  41830. *
  41831. * @param name The material name
  41832. * @param scene The scene the material will be use in.
  41833. */
  41834. function PBRBaseSimpleMaterial(name, scene) {
  41835. var _this = _super.call(this, name, scene) || this;
  41836. /**
  41837. * Number of Simultaneous lights allowed on the material.
  41838. */
  41839. _this.maxSimultaneousLights = 4;
  41840. /**
  41841. * If sets to true, disables all the lights affecting the material.
  41842. */
  41843. _this.disableLighting = false;
  41844. /**
  41845. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41846. */
  41847. _this.invertNormalMapX = false;
  41848. /**
  41849. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41850. */
  41851. _this.invertNormalMapY = false;
  41852. /**
  41853. * Emissivie color used to self-illuminate the model.
  41854. */
  41855. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41856. /**
  41857. * Occlusion Channel Strenght.
  41858. */
  41859. _this.occlusionStrength = 1.0;
  41860. _this.useLightmapAsShadowmap = false;
  41861. _this._useAlphaFromAlbedoTexture = true;
  41862. _this._useAmbientInGrayScale = true;
  41863. return _this;
  41864. }
  41865. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41866. /**
  41867. * Gets the current double sided mode.
  41868. */
  41869. get: function () {
  41870. return this._twoSidedLighting;
  41871. },
  41872. /**
  41873. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41874. */
  41875. set: function (value) {
  41876. if (this._twoSidedLighting === value) {
  41877. return;
  41878. }
  41879. this._twoSidedLighting = value;
  41880. this.backFaceCulling = !value;
  41881. this._markAllSubMeshesAsTexturesDirty();
  41882. },
  41883. enumerable: true,
  41884. configurable: true
  41885. });
  41886. /**
  41887. * Return the active textures of the material.
  41888. */
  41889. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41890. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41891. if (this.environmentTexture) {
  41892. activeTextures.push(this.environmentTexture);
  41893. }
  41894. if (this.normalTexture) {
  41895. activeTextures.push(this.normalTexture);
  41896. }
  41897. if (this.emissiveTexture) {
  41898. activeTextures.push(this.emissiveTexture);
  41899. }
  41900. if (this.occlusionTexture) {
  41901. activeTextures.push(this.occlusionTexture);
  41902. }
  41903. if (this.lightmapTexture) {
  41904. activeTextures.push(this.lightmapTexture);
  41905. }
  41906. return activeTextures;
  41907. };
  41908. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41909. if (_super.prototype.hasTexture.call(this, texture)) {
  41910. return true;
  41911. }
  41912. if (this.lightmapTexture === texture) {
  41913. return true;
  41914. }
  41915. return false;
  41916. };
  41917. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41918. return "PBRBaseSimpleMaterial";
  41919. };
  41920. __decorate([
  41921. BABYLON.serialize(),
  41922. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41923. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41924. __decorate([
  41925. BABYLON.serialize(),
  41926. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41927. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41928. __decorate([
  41929. BABYLON.serializeAsTexture(),
  41930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41931. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41932. __decorate([
  41933. BABYLON.serialize(),
  41934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41935. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41936. __decorate([
  41937. BABYLON.serialize(),
  41938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41939. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41940. __decorate([
  41941. BABYLON.serializeAsTexture(),
  41942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41943. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41944. __decorate([
  41945. BABYLON.serializeAsColor3("emissive"),
  41946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41947. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41948. __decorate([
  41949. BABYLON.serializeAsTexture(),
  41950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41951. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41952. __decorate([
  41953. BABYLON.serialize(),
  41954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41955. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41956. __decorate([
  41957. BABYLON.serializeAsTexture(),
  41958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41959. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41960. __decorate([
  41961. BABYLON.serialize(),
  41962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41963. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41964. __decorate([
  41965. BABYLON.serialize()
  41966. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41967. __decorate([
  41968. BABYLON.serializeAsTexture(),
  41969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41970. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41971. __decorate([
  41972. BABYLON.serialize(),
  41973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41974. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41975. return PBRBaseSimpleMaterial;
  41976. }(BABYLON.PBRBaseMaterial));
  41977. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41978. })(BABYLON || (BABYLON = {}));
  41979. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41980. var BABYLON;
  41981. (function (BABYLON) {
  41982. /**
  41983. * The Physically based material of BJS.
  41984. *
  41985. * This offers the main features of a standard PBR material.
  41986. * For more information, please refer to the documentation :
  41987. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41988. */
  41989. var PBRMaterial = /** @class */ (function (_super) {
  41990. __extends(PBRMaterial, _super);
  41991. /**
  41992. * Instantiates a new PBRMaterial instance.
  41993. *
  41994. * @param name The material name
  41995. * @param scene The scene the material will be use in.
  41996. */
  41997. function PBRMaterial(name, scene) {
  41998. var _this = _super.call(this, name, scene) || this;
  41999. /**
  42000. * Intensity of the direct lights e.g. the four lights available in your scene.
  42001. * This impacts both the direct diffuse and specular highlights.
  42002. */
  42003. _this.directIntensity = 1.0;
  42004. /**
  42005. * Intensity of the emissive part of the material.
  42006. * This helps controlling the emissive effect without modifying the emissive color.
  42007. */
  42008. _this.emissiveIntensity = 1.0;
  42009. /**
  42010. * Intensity of the environment e.g. how much the environment will light the object
  42011. * either through harmonics for rough material or through the refelction for shiny ones.
  42012. */
  42013. _this.environmentIntensity = 1.0;
  42014. /**
  42015. * This is a special control allowing the reduction of the specular highlights coming from the
  42016. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42017. */
  42018. _this.specularIntensity = 1.0;
  42019. /**
  42020. * Debug Control allowing disabling the bump map on this material.
  42021. */
  42022. _this.disableBumpMap = false;
  42023. /**
  42024. * AKA Occlusion Texture Intensity in other nomenclature.
  42025. */
  42026. _this.ambientTextureStrength = 1.0;
  42027. /**
  42028. * The color of a material in ambient lighting.
  42029. */
  42030. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42031. /**
  42032. * AKA Diffuse Color in other nomenclature.
  42033. */
  42034. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42035. /**
  42036. * AKA Specular Color in other nomenclature.
  42037. */
  42038. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42039. /**
  42040. * The color reflected from the material.
  42041. */
  42042. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42043. /**
  42044. * The color emitted from the material.
  42045. */
  42046. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42047. /**
  42048. * AKA Glossiness in other nomenclature.
  42049. */
  42050. _this.microSurface = 1.0;
  42051. /**
  42052. * source material index of refraction (IOR)' / 'destination material IOR.
  42053. */
  42054. _this.indexOfRefraction = 0.66;
  42055. /**
  42056. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42057. */
  42058. _this.invertRefractionY = false;
  42059. /**
  42060. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42061. * Materials half opaque for instance using refraction could benefit from this control.
  42062. */
  42063. _this.linkRefractionWithTransparency = false;
  42064. _this.useLightmapAsShadowmap = false;
  42065. /**
  42066. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42067. */
  42068. _this.useAlphaFromAlbedoTexture = false;
  42069. /**
  42070. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42071. */
  42072. _this.forceAlphaTest = false;
  42073. /**
  42074. * Defines the alpha limits in alpha test mode.
  42075. */
  42076. _this.alphaCutOff = 0.4;
  42077. /**
  42078. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42079. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42080. */
  42081. _this.useSpecularOverAlpha = true;
  42082. /**
  42083. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42084. */
  42085. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42086. /**
  42087. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42088. */
  42089. _this.useRoughnessFromMetallicTextureAlpha = true;
  42090. /**
  42091. * Specifies if the metallic texture contains the roughness information in its green channel.
  42092. */
  42093. _this.useRoughnessFromMetallicTextureGreen = false;
  42094. /**
  42095. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42096. */
  42097. _this.useMetallnessFromMetallicTextureBlue = false;
  42098. /**
  42099. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42100. */
  42101. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42102. /**
  42103. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42104. */
  42105. _this.useAmbientInGrayScale = false;
  42106. /**
  42107. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42108. * The material will try to infer what glossiness each pixel should be.
  42109. */
  42110. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42111. /**
  42112. * BJS is using an harcoded light falloff based on a manually sets up range.
  42113. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42114. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42115. */
  42116. _this.usePhysicalLightFalloff = true;
  42117. /**
  42118. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42119. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42120. */
  42121. _this.useRadianceOverAlpha = true;
  42122. /**
  42123. * Allows using an object space normal map (instead of tangent space).
  42124. */
  42125. _this.useObjectSpaceNormalMap = false;
  42126. /**
  42127. * Allows using the bump map in parallax mode.
  42128. */
  42129. _this.useParallax = false;
  42130. /**
  42131. * Allows using the bump map in parallax occlusion mode.
  42132. */
  42133. _this.useParallaxOcclusion = false;
  42134. /**
  42135. * Controls the scale bias of the parallax mode.
  42136. */
  42137. _this.parallaxScaleBias = 0.05;
  42138. /**
  42139. * If sets to true, disables all the lights affecting the material.
  42140. */
  42141. _this.disableLighting = false;
  42142. /**
  42143. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42144. */
  42145. _this.forceIrradianceInFragment = false;
  42146. /**
  42147. * Number of Simultaneous lights allowed on the material.
  42148. */
  42149. _this.maxSimultaneousLights = 4;
  42150. /**
  42151. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42152. */
  42153. _this.invertNormalMapX = false;
  42154. /**
  42155. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42156. */
  42157. _this.invertNormalMapY = false;
  42158. /**
  42159. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42160. */
  42161. _this.twoSidedLighting = false;
  42162. /**
  42163. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42164. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42165. */
  42166. _this.useAlphaFresnel = false;
  42167. /**
  42168. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42169. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42170. */
  42171. _this.useLinearAlphaFresnel = false;
  42172. /**
  42173. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42174. * And/Or occlude the blended part.
  42175. */
  42176. _this.environmentBRDFTexture = null;
  42177. /**
  42178. * Force normal to face away from face.
  42179. */
  42180. _this.forceNormalForward = false;
  42181. /**
  42182. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42183. * makes the reflect vector face the model (under horizon).
  42184. */
  42185. _this.useHorizonOcclusion = true;
  42186. /**
  42187. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42188. * too much the area relying on ambient texture to define their ambient occlusion.
  42189. */
  42190. _this.useRadianceOcclusion = true;
  42191. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42192. return _this;
  42193. }
  42194. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42195. /**
  42196. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42197. */
  42198. get: function () {
  42199. return this._PBRMATERIAL_OPAQUE;
  42200. },
  42201. enumerable: true,
  42202. configurable: true
  42203. });
  42204. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42205. /**
  42206. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42207. */
  42208. get: function () {
  42209. return this._PBRMATERIAL_ALPHATEST;
  42210. },
  42211. enumerable: true,
  42212. configurable: true
  42213. });
  42214. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42215. /**
  42216. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42217. */
  42218. get: function () {
  42219. return this._PBRMATERIAL_ALPHABLEND;
  42220. },
  42221. enumerable: true,
  42222. configurable: true
  42223. });
  42224. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42225. /**
  42226. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42227. * They are also discarded below the alpha cutoff threshold to improve performances.
  42228. */
  42229. get: function () {
  42230. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42231. },
  42232. enumerable: true,
  42233. configurable: true
  42234. });
  42235. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42236. /**
  42237. * Gets the image processing configuration used either in this material.
  42238. */
  42239. get: function () {
  42240. return this._imageProcessingConfiguration;
  42241. },
  42242. /**
  42243. * Sets the Default image processing configuration used either in the this material.
  42244. *
  42245. * If sets to null, the scene one is in use.
  42246. */
  42247. set: function (value) {
  42248. this._attachImageProcessingConfiguration(value);
  42249. // Ensure the effect will be rebuilt.
  42250. this._markAllSubMeshesAsTexturesDirty();
  42251. },
  42252. enumerable: true,
  42253. configurable: true
  42254. });
  42255. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42256. /**
  42257. * Gets wether the color curves effect is enabled.
  42258. */
  42259. get: function () {
  42260. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42261. },
  42262. /**
  42263. * Sets wether the color curves effect is enabled.
  42264. */
  42265. set: function (value) {
  42266. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42267. },
  42268. enumerable: true,
  42269. configurable: true
  42270. });
  42271. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42272. /**
  42273. * Gets wether the color grading effect is enabled.
  42274. */
  42275. get: function () {
  42276. return this.imageProcessingConfiguration.colorGradingEnabled;
  42277. },
  42278. /**
  42279. * Gets wether the color grading effect is enabled.
  42280. */
  42281. set: function (value) {
  42282. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42283. },
  42284. enumerable: true,
  42285. configurable: true
  42286. });
  42287. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42288. /**
  42289. * Gets wether tonemapping is enabled or not.
  42290. */
  42291. get: function () {
  42292. return this._imageProcessingConfiguration.toneMappingEnabled;
  42293. },
  42294. /**
  42295. * Sets wether tonemapping is enabled or not
  42296. */
  42297. set: function (value) {
  42298. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42299. },
  42300. enumerable: true,
  42301. configurable: true
  42302. });
  42303. ;
  42304. ;
  42305. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42306. /**
  42307. * The camera exposure used on this material.
  42308. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42309. * This corresponds to a photographic exposure.
  42310. */
  42311. get: function () {
  42312. return this._imageProcessingConfiguration.exposure;
  42313. },
  42314. /**
  42315. * The camera exposure used on this material.
  42316. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42317. * This corresponds to a photographic exposure.
  42318. */
  42319. set: function (value) {
  42320. this._imageProcessingConfiguration.exposure = value;
  42321. },
  42322. enumerable: true,
  42323. configurable: true
  42324. });
  42325. ;
  42326. ;
  42327. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42328. /**
  42329. * Gets The camera contrast used on this material.
  42330. */
  42331. get: function () {
  42332. return this._imageProcessingConfiguration.contrast;
  42333. },
  42334. /**
  42335. * Sets The camera contrast used on this material.
  42336. */
  42337. set: function (value) {
  42338. this._imageProcessingConfiguration.contrast = value;
  42339. },
  42340. enumerable: true,
  42341. configurable: true
  42342. });
  42343. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42344. /**
  42345. * Gets the Color Grading 2D Lookup Texture.
  42346. */
  42347. get: function () {
  42348. return this._imageProcessingConfiguration.colorGradingTexture;
  42349. },
  42350. /**
  42351. * Sets the Color Grading 2D Lookup Texture.
  42352. */
  42353. set: function (value) {
  42354. this._imageProcessingConfiguration.colorGradingTexture = value;
  42355. },
  42356. enumerable: true,
  42357. configurable: true
  42358. });
  42359. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42360. /**
  42361. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42362. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42363. * 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;
  42364. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42365. */
  42366. get: function () {
  42367. return this._imageProcessingConfiguration.colorCurves;
  42368. },
  42369. /**
  42370. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42371. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42372. * 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;
  42373. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42374. */
  42375. set: function (value) {
  42376. this._imageProcessingConfiguration.colorCurves = value;
  42377. },
  42378. enumerable: true,
  42379. configurable: true
  42380. });
  42381. /**
  42382. * Returns the name of this material class.
  42383. */
  42384. PBRMaterial.prototype.getClassName = function () {
  42385. return "PBRMaterial";
  42386. };
  42387. /**
  42388. * Returns an array of the actively used textures.
  42389. * @returns - Array of BaseTextures
  42390. */
  42391. PBRMaterial.prototype.getActiveTextures = function () {
  42392. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42393. if (this._albedoTexture) {
  42394. activeTextures.push(this._albedoTexture);
  42395. }
  42396. if (this._ambientTexture) {
  42397. activeTextures.push(this._ambientTexture);
  42398. }
  42399. if (this._opacityTexture) {
  42400. activeTextures.push(this._opacityTexture);
  42401. }
  42402. if (this._reflectionTexture) {
  42403. activeTextures.push(this._reflectionTexture);
  42404. }
  42405. if (this._emissiveTexture) {
  42406. activeTextures.push(this._emissiveTexture);
  42407. }
  42408. if (this._reflectivityTexture) {
  42409. activeTextures.push(this._reflectivityTexture);
  42410. }
  42411. if (this._metallicTexture) {
  42412. activeTextures.push(this._metallicTexture);
  42413. }
  42414. if (this._microSurfaceTexture) {
  42415. activeTextures.push(this._microSurfaceTexture);
  42416. }
  42417. if (this._bumpTexture) {
  42418. activeTextures.push(this._bumpTexture);
  42419. }
  42420. if (this._lightmapTexture) {
  42421. activeTextures.push(this._lightmapTexture);
  42422. }
  42423. if (this._refractionTexture) {
  42424. activeTextures.push(this._refractionTexture);
  42425. }
  42426. return activeTextures;
  42427. };
  42428. /**
  42429. * Checks to see if a texture is used in the material.
  42430. * @param texture - Base texture to use.
  42431. * @returns - Boolean specifying if a texture is used in the material.
  42432. */
  42433. PBRMaterial.prototype.hasTexture = function (texture) {
  42434. if (_super.prototype.hasTexture.call(this, texture)) {
  42435. return true;
  42436. }
  42437. if (this._albedoTexture === texture) {
  42438. return true;
  42439. }
  42440. if (this._ambientTexture === texture) {
  42441. return true;
  42442. }
  42443. if (this._opacityTexture === texture) {
  42444. return true;
  42445. }
  42446. if (this._reflectionTexture === texture) {
  42447. return true;
  42448. }
  42449. if (this._reflectivityTexture === texture) {
  42450. return true;
  42451. }
  42452. if (this._metallicTexture === texture) {
  42453. return true;
  42454. }
  42455. if (this._microSurfaceTexture === texture) {
  42456. return true;
  42457. }
  42458. if (this._bumpTexture === texture) {
  42459. return true;
  42460. }
  42461. if (this._lightmapTexture === texture) {
  42462. return true;
  42463. }
  42464. if (this._refractionTexture === texture) {
  42465. return true;
  42466. }
  42467. return false;
  42468. };
  42469. /**
  42470. * Makes a duplicate of the current material.
  42471. * @param name - name to use for the new material.
  42472. */
  42473. PBRMaterial.prototype.clone = function (name) {
  42474. var _this = this;
  42475. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42476. clone.id = name;
  42477. clone.name = name;
  42478. return clone;
  42479. };
  42480. /**
  42481. * Serializes this PBR Material.
  42482. * @returns - An object with the serialized material.
  42483. */
  42484. PBRMaterial.prototype.serialize = function () {
  42485. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42486. serializationObject.customType = "BABYLON.PBRMaterial";
  42487. return serializationObject;
  42488. };
  42489. // Statics
  42490. /**
  42491. * Parses a PBR Material from a serialized object.
  42492. * @param source - Serialized object.
  42493. * @param scene - BJS scene instance.
  42494. * @param rootUrl - url for the scene object
  42495. * @returns - PBRMaterial
  42496. */
  42497. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42498. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42499. };
  42500. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42501. /**
  42502. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42503. */
  42504. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42505. /**
  42506. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42507. */
  42508. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42509. /**
  42510. * 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.
  42511. * They are also discarded below the alpha cutoff threshold to improve performances.
  42512. */
  42513. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42514. __decorate([
  42515. BABYLON.serialize(),
  42516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42517. ], PBRMaterial.prototype, "directIntensity", void 0);
  42518. __decorate([
  42519. BABYLON.serialize(),
  42520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42521. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42522. __decorate([
  42523. BABYLON.serialize(),
  42524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42525. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42526. __decorate([
  42527. BABYLON.serialize(),
  42528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42529. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42530. __decorate([
  42531. BABYLON.serialize(),
  42532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42533. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42534. __decorate([
  42535. BABYLON.serializeAsTexture(),
  42536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42537. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42538. __decorate([
  42539. BABYLON.serializeAsTexture(),
  42540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42541. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42542. __decorate([
  42543. BABYLON.serialize(),
  42544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42545. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42546. __decorate([
  42547. BABYLON.serializeAsTexture(),
  42548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42549. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42550. __decorate([
  42551. BABYLON.serializeAsTexture(),
  42552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42553. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42554. __decorate([
  42555. BABYLON.serializeAsTexture(),
  42556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42557. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42558. __decorate([
  42559. BABYLON.serializeAsTexture(),
  42560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42561. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42562. __decorate([
  42563. BABYLON.serializeAsTexture(),
  42564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42565. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42566. __decorate([
  42567. BABYLON.serialize(),
  42568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42569. ], PBRMaterial.prototype, "metallic", void 0);
  42570. __decorate([
  42571. BABYLON.serialize(),
  42572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42573. ], PBRMaterial.prototype, "roughness", void 0);
  42574. __decorate([
  42575. BABYLON.serializeAsTexture(),
  42576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42577. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42578. __decorate([
  42579. BABYLON.serializeAsTexture(),
  42580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42581. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42582. __decorate([
  42583. BABYLON.serializeAsTexture(),
  42584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42585. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42586. __decorate([
  42587. BABYLON.serializeAsTexture(),
  42588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42589. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42590. __decorate([
  42591. BABYLON.serializeAsColor3("ambient"),
  42592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42593. ], PBRMaterial.prototype, "ambientColor", void 0);
  42594. __decorate([
  42595. BABYLON.serializeAsColor3("albedo"),
  42596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42597. ], PBRMaterial.prototype, "albedoColor", void 0);
  42598. __decorate([
  42599. BABYLON.serializeAsColor3("reflectivity"),
  42600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42601. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42602. __decorate([
  42603. BABYLON.serializeAsColor3("reflection"),
  42604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42605. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42606. __decorate([
  42607. BABYLON.serializeAsColor3("emissive"),
  42608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42609. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42610. __decorate([
  42611. BABYLON.serialize(),
  42612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42613. ], PBRMaterial.prototype, "microSurface", void 0);
  42614. __decorate([
  42615. BABYLON.serialize(),
  42616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42617. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42618. __decorate([
  42619. BABYLON.serialize(),
  42620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42621. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42622. __decorate([
  42623. BABYLON.serialize(),
  42624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42625. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42626. __decorate([
  42627. BABYLON.serialize(),
  42628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42629. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42630. __decorate([
  42631. BABYLON.serialize(),
  42632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42633. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42634. __decorate([
  42635. BABYLON.serialize(),
  42636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42637. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42638. __decorate([
  42639. BABYLON.serialize(),
  42640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42641. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42642. __decorate([
  42643. BABYLON.serialize(),
  42644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42645. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42646. __decorate([
  42647. BABYLON.serialize(),
  42648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42649. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42650. __decorate([
  42651. BABYLON.serialize(),
  42652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42653. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42654. __decorate([
  42655. BABYLON.serialize(),
  42656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42657. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42658. __decorate([
  42659. BABYLON.serialize(),
  42660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42661. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42662. __decorate([
  42663. BABYLON.serialize(),
  42664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42665. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42666. __decorate([
  42667. BABYLON.serialize(),
  42668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42669. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42670. __decorate([
  42671. BABYLON.serialize(),
  42672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42673. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42674. __decorate([
  42675. BABYLON.serialize(),
  42676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42677. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42678. __decorate([
  42679. BABYLON.serialize(),
  42680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42681. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42682. __decorate([
  42683. BABYLON.serialize(),
  42684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42685. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42686. __decorate([
  42687. BABYLON.serialize(),
  42688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42689. ], PBRMaterial.prototype, "useParallax", void 0);
  42690. __decorate([
  42691. BABYLON.serialize(),
  42692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42693. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42694. __decorate([
  42695. BABYLON.serialize(),
  42696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42697. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42698. __decorate([
  42699. BABYLON.serialize(),
  42700. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42701. ], PBRMaterial.prototype, "disableLighting", void 0);
  42702. __decorate([
  42703. BABYLON.serialize(),
  42704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42705. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42706. __decorate([
  42707. BABYLON.serialize(),
  42708. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42709. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42710. __decorate([
  42711. BABYLON.serialize(),
  42712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42713. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42714. __decorate([
  42715. BABYLON.serialize(),
  42716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42717. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42718. __decorate([
  42719. BABYLON.serialize(),
  42720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42721. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42722. __decorate([
  42723. BABYLON.serialize(),
  42724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42725. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42726. __decorate([
  42727. BABYLON.serialize(),
  42728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42729. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42730. __decorate([
  42731. BABYLON.serializeAsTexture(),
  42732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42733. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42734. __decorate([
  42735. BABYLON.serialize(),
  42736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42737. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42738. __decorate([
  42739. BABYLON.serialize(),
  42740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42741. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42742. __decorate([
  42743. BABYLON.serialize(),
  42744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42745. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42746. return PBRMaterial;
  42747. }(BABYLON.PBRBaseMaterial));
  42748. BABYLON.PBRMaterial = PBRMaterial;
  42749. })(BABYLON || (BABYLON = {}));
  42750. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42751. var BABYLON;
  42752. (function (BABYLON) {
  42753. /**
  42754. * The PBR material of BJS following the metal roughness convention.
  42755. *
  42756. * This fits to the PBR convention in the GLTF definition:
  42757. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42758. */
  42759. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42760. __extends(PBRMetallicRoughnessMaterial, _super);
  42761. /**
  42762. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42763. *
  42764. * @param name The material name
  42765. * @param scene The scene the material will be use in.
  42766. */
  42767. function PBRMetallicRoughnessMaterial(name, scene) {
  42768. var _this = _super.call(this, name, scene) || this;
  42769. _this._useRoughnessFromMetallicTextureAlpha = false;
  42770. _this._useRoughnessFromMetallicTextureGreen = true;
  42771. _this._useMetallnessFromMetallicTextureBlue = true;
  42772. _this.metallic = 1.0;
  42773. _this.roughness = 1.0;
  42774. return _this;
  42775. }
  42776. /**
  42777. * Return the currrent class name of the material.
  42778. */
  42779. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42780. return "PBRMetallicRoughnessMaterial";
  42781. };
  42782. /**
  42783. * Return the active textures of the material.
  42784. */
  42785. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42786. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42787. if (this.baseTexture) {
  42788. activeTextures.push(this.baseTexture);
  42789. }
  42790. if (this.metallicRoughnessTexture) {
  42791. activeTextures.push(this.metallicRoughnessTexture);
  42792. }
  42793. return activeTextures;
  42794. };
  42795. /**
  42796. * Checks to see if a texture is used in the material.
  42797. * @param texture - Base texture to use.
  42798. * @returns - Boolean specifying if a texture is used in the material.
  42799. */
  42800. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42801. if (_super.prototype.hasTexture.call(this, texture)) {
  42802. return true;
  42803. }
  42804. if (this.baseTexture === texture) {
  42805. return true;
  42806. }
  42807. if (this.metallicRoughnessTexture === texture) {
  42808. return true;
  42809. }
  42810. return false;
  42811. };
  42812. /**
  42813. * Makes a duplicate of the current material.
  42814. * @param name - name to use for the new material.
  42815. */
  42816. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42817. var _this = this;
  42818. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42819. clone.id = name;
  42820. clone.name = name;
  42821. return clone;
  42822. };
  42823. /**
  42824. * Serialize the material to a parsable JSON object.
  42825. */
  42826. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42827. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42828. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42829. return serializationObject;
  42830. };
  42831. /**
  42832. * Parses a JSON object correponding to the serialize function.
  42833. */
  42834. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42835. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42836. };
  42837. __decorate([
  42838. BABYLON.serializeAsColor3(),
  42839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42840. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42841. __decorate([
  42842. BABYLON.serializeAsTexture(),
  42843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42844. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42845. __decorate([
  42846. BABYLON.serialize(),
  42847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42848. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42849. __decorate([
  42850. BABYLON.serialize(),
  42851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42852. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42853. __decorate([
  42854. BABYLON.serializeAsTexture(),
  42855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42856. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42857. return PBRMetallicRoughnessMaterial;
  42858. }(BABYLON.PBRBaseSimpleMaterial));
  42859. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42860. })(BABYLON || (BABYLON = {}));
  42861. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42862. var BABYLON;
  42863. (function (BABYLON) {
  42864. /**
  42865. * The PBR material of BJS following the specular glossiness convention.
  42866. *
  42867. * This fits to the PBR convention in the GLTF definition:
  42868. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42869. */
  42870. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42871. __extends(PBRSpecularGlossinessMaterial, _super);
  42872. /**
  42873. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42874. *
  42875. * @param name The material name
  42876. * @param scene The scene the material will be use in.
  42877. */
  42878. function PBRSpecularGlossinessMaterial(name, scene) {
  42879. var _this = _super.call(this, name, scene) || this;
  42880. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42881. return _this;
  42882. }
  42883. /**
  42884. * Return the currrent class name of the material.
  42885. */
  42886. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42887. return "PBRSpecularGlossinessMaterial";
  42888. };
  42889. /**
  42890. * Return the active textures of the material.
  42891. */
  42892. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42893. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42894. if (this.diffuseTexture) {
  42895. activeTextures.push(this.diffuseTexture);
  42896. }
  42897. if (this.specularGlossinessTexture) {
  42898. activeTextures.push(this.specularGlossinessTexture);
  42899. }
  42900. return activeTextures;
  42901. };
  42902. /**
  42903. * Checks to see if a texture is used in the material.
  42904. * @param texture - Base texture to use.
  42905. * @returns - Boolean specifying if a texture is used in the material.
  42906. */
  42907. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42908. if (_super.prototype.hasTexture.call(this, texture)) {
  42909. return true;
  42910. }
  42911. if (this.diffuseTexture === texture) {
  42912. return true;
  42913. }
  42914. if (this.specularGlossinessTexture === texture) {
  42915. return true;
  42916. }
  42917. return false;
  42918. };
  42919. /**
  42920. * Makes a duplicate of the current material.
  42921. * @param name - name to use for the new material.
  42922. */
  42923. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42924. var _this = this;
  42925. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42926. clone.id = name;
  42927. clone.name = name;
  42928. return clone;
  42929. };
  42930. /**
  42931. * Serialize the material to a parsable JSON object.
  42932. */
  42933. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42934. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42935. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42936. return serializationObject;
  42937. };
  42938. /**
  42939. * Parses a JSON object correponding to the serialize function.
  42940. */
  42941. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42942. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42943. };
  42944. __decorate([
  42945. BABYLON.serializeAsColor3("diffuse"),
  42946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42947. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42948. __decorate([
  42949. BABYLON.serializeAsTexture(),
  42950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42951. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42952. __decorate([
  42953. BABYLON.serializeAsColor3("specular"),
  42954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42955. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42956. __decorate([
  42957. BABYLON.serialize(),
  42958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42959. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42960. __decorate([
  42961. BABYLON.serializeAsTexture(),
  42962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42963. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42964. return PBRSpecularGlossinessMaterial;
  42965. }(BABYLON.PBRBaseSimpleMaterial));
  42966. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42967. })(BABYLON || (BABYLON = {}));
  42968. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42969. var BABYLON;
  42970. (function (BABYLON) {
  42971. BABYLON.CameraInputTypes = {};
  42972. var CameraInputsManager = /** @class */ (function () {
  42973. function CameraInputsManager(camera) {
  42974. this.attached = {};
  42975. this.camera = camera;
  42976. this.checkInputs = function () { };
  42977. }
  42978. /**
  42979. * Add an input method to a camera.
  42980. * builtin inputs example: camera.inputs.addGamepad();
  42981. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42982. * @param input camera input method
  42983. */
  42984. CameraInputsManager.prototype.add = function (input) {
  42985. var type = input.getSimpleName();
  42986. if (this.attached[type]) {
  42987. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42988. return;
  42989. }
  42990. this.attached[type] = input;
  42991. input.camera = this.camera;
  42992. //for checkInputs, we are dynamically creating a function
  42993. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42994. if (input.checkInputs) {
  42995. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42996. }
  42997. if (this.attachedElement) {
  42998. input.attachControl(this.attachedElement);
  42999. }
  43000. };
  43001. /**
  43002. * Remove a specific input method from a camera
  43003. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43004. * @param inputToRemove camera input method
  43005. */
  43006. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43007. for (var cam in this.attached) {
  43008. var input = this.attached[cam];
  43009. if (input === inputToRemove) {
  43010. input.detachControl(this.attachedElement);
  43011. input.camera = null;
  43012. delete this.attached[cam];
  43013. this.rebuildInputCheck();
  43014. }
  43015. }
  43016. };
  43017. CameraInputsManager.prototype.removeByType = function (inputType) {
  43018. for (var cam in this.attached) {
  43019. var input = this.attached[cam];
  43020. if (input.getClassName() === inputType) {
  43021. input.detachControl(this.attachedElement);
  43022. input.camera = null;
  43023. delete this.attached[cam];
  43024. this.rebuildInputCheck();
  43025. }
  43026. }
  43027. };
  43028. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43029. var current = this.checkInputs;
  43030. return function () {
  43031. current();
  43032. fn();
  43033. };
  43034. };
  43035. CameraInputsManager.prototype.attachInput = function (input) {
  43036. if (this.attachedElement) {
  43037. input.attachControl(this.attachedElement, this.noPreventDefault);
  43038. }
  43039. };
  43040. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43041. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43042. if (this.attachedElement) {
  43043. return;
  43044. }
  43045. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43046. this.attachedElement = element;
  43047. this.noPreventDefault = noPreventDefault;
  43048. for (var cam in this.attached) {
  43049. this.attached[cam].attachControl(element, noPreventDefault);
  43050. }
  43051. };
  43052. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43053. if (disconnect === void 0) { disconnect = false; }
  43054. if (this.attachedElement !== element) {
  43055. return;
  43056. }
  43057. for (var cam in this.attached) {
  43058. this.attached[cam].detachControl(element);
  43059. if (disconnect) {
  43060. this.attached[cam].camera = null;
  43061. }
  43062. }
  43063. this.attachedElement = null;
  43064. };
  43065. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43066. this.checkInputs = function () { };
  43067. for (var cam in this.attached) {
  43068. var input = this.attached[cam];
  43069. if (input.checkInputs) {
  43070. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43071. }
  43072. }
  43073. };
  43074. /**
  43075. * Remove all attached input methods from a camera
  43076. */
  43077. CameraInputsManager.prototype.clear = function () {
  43078. if (this.attachedElement) {
  43079. this.detachElement(this.attachedElement, true);
  43080. }
  43081. this.attached = {};
  43082. this.attachedElement = null;
  43083. this.checkInputs = function () { };
  43084. };
  43085. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43086. var inputs = {};
  43087. for (var cam in this.attached) {
  43088. var input = this.attached[cam];
  43089. var res = BABYLON.SerializationHelper.Serialize(input);
  43090. inputs[input.getClassName()] = res;
  43091. }
  43092. serializedCamera.inputsmgr = inputs;
  43093. };
  43094. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43095. var parsedInputs = parsedCamera.inputsmgr;
  43096. if (parsedInputs) {
  43097. this.clear();
  43098. for (var n in parsedInputs) {
  43099. var construct = BABYLON.CameraInputTypes[n];
  43100. if (construct) {
  43101. var parsedinput = parsedInputs[n];
  43102. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43103. this.add(input);
  43104. }
  43105. }
  43106. }
  43107. else {
  43108. //2016-03-08 this part is for managing backward compatibility
  43109. for (var n in this.attached) {
  43110. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43111. if (construct) {
  43112. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43113. this.remove(this.attached[n]);
  43114. this.add(input);
  43115. }
  43116. }
  43117. }
  43118. };
  43119. return CameraInputsManager;
  43120. }());
  43121. BABYLON.CameraInputsManager = CameraInputsManager;
  43122. })(BABYLON || (BABYLON = {}));
  43123. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43124. var BABYLON;
  43125. (function (BABYLON) {
  43126. var TargetCamera = /** @class */ (function (_super) {
  43127. __extends(TargetCamera, _super);
  43128. function TargetCamera(name, position, scene) {
  43129. var _this = _super.call(this, name, position, scene) || this;
  43130. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43131. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43132. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43133. _this.speed = 2.0;
  43134. _this.noRotationConstraint = false;
  43135. _this.lockedTarget = null;
  43136. _this._currentTarget = BABYLON.Vector3.Zero();
  43137. _this._viewMatrix = BABYLON.Matrix.Zero();
  43138. _this._camMatrix = BABYLON.Matrix.Zero();
  43139. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43140. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43141. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43142. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43143. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43144. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43145. _this._tempMatrix = BABYLON.Matrix.Zero();
  43146. return _this;
  43147. }
  43148. TargetCamera.prototype.getFrontPosition = function (distance) {
  43149. this.getWorldMatrix();
  43150. var direction = this.getTarget().subtract(this.position);
  43151. direction.normalize();
  43152. direction.scaleInPlace(distance);
  43153. return this.globalPosition.add(direction);
  43154. };
  43155. TargetCamera.prototype._getLockedTargetPosition = function () {
  43156. if (!this.lockedTarget) {
  43157. return null;
  43158. }
  43159. if (this.lockedTarget.absolutePosition) {
  43160. this.lockedTarget.computeWorldMatrix();
  43161. }
  43162. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43163. };
  43164. TargetCamera.prototype.storeState = function () {
  43165. this._storedPosition = this.position.clone();
  43166. this._storedRotation = this.rotation.clone();
  43167. if (this.rotationQuaternion) {
  43168. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43169. }
  43170. return _super.prototype.storeState.call(this);
  43171. };
  43172. /**
  43173. * Restored camera state. You must call storeState() first
  43174. */
  43175. TargetCamera.prototype._restoreStateValues = function () {
  43176. if (!_super.prototype._restoreStateValues.call(this)) {
  43177. return false;
  43178. }
  43179. this.position = this._storedPosition.clone();
  43180. this.rotation = this._storedRotation.clone();
  43181. if (this.rotationQuaternion) {
  43182. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43183. }
  43184. this.cameraDirection.copyFromFloats(0, 0, 0);
  43185. this.cameraRotation.copyFromFloats(0, 0);
  43186. return true;
  43187. };
  43188. // Cache
  43189. TargetCamera.prototype._initCache = function () {
  43190. _super.prototype._initCache.call(this);
  43191. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43192. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43193. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43194. };
  43195. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43196. if (!ignoreParentClass) {
  43197. _super.prototype._updateCache.call(this);
  43198. }
  43199. var lockedTargetPosition = this._getLockedTargetPosition();
  43200. if (!lockedTargetPosition) {
  43201. this._cache.lockedTarget = null;
  43202. }
  43203. else {
  43204. if (!this._cache.lockedTarget) {
  43205. this._cache.lockedTarget = lockedTargetPosition.clone();
  43206. }
  43207. else {
  43208. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43209. }
  43210. }
  43211. this._cache.rotation.copyFrom(this.rotation);
  43212. if (this.rotationQuaternion)
  43213. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43214. };
  43215. // Synchronized
  43216. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43217. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43218. return false;
  43219. }
  43220. var lockedTargetPosition = this._getLockedTargetPosition();
  43221. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43222. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43223. };
  43224. // Methods
  43225. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43226. var engine = this.getEngine();
  43227. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43228. };
  43229. // Target
  43230. TargetCamera.prototype.setTarget = function (target) {
  43231. this.upVector.normalize();
  43232. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43233. this._camMatrix.invert();
  43234. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43235. var vDir = target.subtract(this.position);
  43236. if (vDir.x >= 0.0) {
  43237. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43238. }
  43239. else {
  43240. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43241. }
  43242. this.rotation.z = 0;
  43243. if (isNaN(this.rotation.x)) {
  43244. this.rotation.x = 0;
  43245. }
  43246. if (isNaN(this.rotation.y)) {
  43247. this.rotation.y = 0;
  43248. }
  43249. if (isNaN(this.rotation.z)) {
  43250. this.rotation.z = 0;
  43251. }
  43252. if (this.rotationQuaternion) {
  43253. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43254. }
  43255. };
  43256. /**
  43257. * Return the current target position of the camera. This value is expressed in local space.
  43258. */
  43259. TargetCamera.prototype.getTarget = function () {
  43260. return this._currentTarget;
  43261. };
  43262. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43263. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43264. };
  43265. TargetCamera.prototype._updatePosition = function () {
  43266. if (this.parent) {
  43267. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43268. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43269. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43270. return;
  43271. }
  43272. this.position.addInPlace(this.cameraDirection);
  43273. };
  43274. TargetCamera.prototype._checkInputs = function () {
  43275. var needToMove = this._decideIfNeedsToMove();
  43276. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43277. // Move
  43278. if (needToMove) {
  43279. this._updatePosition();
  43280. }
  43281. // Rotate
  43282. if (needToRotate) {
  43283. this.rotation.x += this.cameraRotation.x;
  43284. this.rotation.y += this.cameraRotation.y;
  43285. //rotate, if quaternion is set and rotation was used
  43286. if (this.rotationQuaternion) {
  43287. var len = this.rotation.lengthSquared();
  43288. if (len) {
  43289. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43290. }
  43291. }
  43292. if (!this.noRotationConstraint) {
  43293. var limit = (Math.PI / 2) * 0.95;
  43294. if (this.rotation.x > limit)
  43295. this.rotation.x = limit;
  43296. if (this.rotation.x < -limit)
  43297. this.rotation.x = -limit;
  43298. }
  43299. }
  43300. // Inertia
  43301. if (needToMove) {
  43302. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43303. this.cameraDirection.x = 0;
  43304. }
  43305. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43306. this.cameraDirection.y = 0;
  43307. }
  43308. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43309. this.cameraDirection.z = 0;
  43310. }
  43311. this.cameraDirection.scaleInPlace(this.inertia);
  43312. }
  43313. if (needToRotate) {
  43314. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43315. this.cameraRotation.x = 0;
  43316. }
  43317. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43318. this.cameraRotation.y = 0;
  43319. }
  43320. this.cameraRotation.scaleInPlace(this.inertia);
  43321. }
  43322. _super.prototype._checkInputs.call(this);
  43323. };
  43324. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43325. if (this.rotationQuaternion) {
  43326. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43327. }
  43328. else {
  43329. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43330. }
  43331. //update the up vector!
  43332. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43333. };
  43334. TargetCamera.prototype._getViewMatrix = function () {
  43335. if (this.lockedTarget) {
  43336. this.setTarget(this._getLockedTargetPosition());
  43337. }
  43338. // Compute
  43339. this._updateCameraRotationMatrix();
  43340. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43341. // Computing target and final matrix
  43342. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43343. if (this.getScene().useRightHandedSystem) {
  43344. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43345. }
  43346. else {
  43347. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43348. }
  43349. return this._viewMatrix;
  43350. };
  43351. /**
  43352. * @override
  43353. * Override Camera.createRigCamera
  43354. */
  43355. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43356. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43357. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43358. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43359. if (!this.rotationQuaternion) {
  43360. this.rotationQuaternion = new BABYLON.Quaternion();
  43361. }
  43362. rigCamera._cameraRigParams = {};
  43363. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43364. }
  43365. return rigCamera;
  43366. }
  43367. return null;
  43368. };
  43369. /**
  43370. * @override
  43371. * Override Camera._updateRigCameras
  43372. */
  43373. TargetCamera.prototype._updateRigCameras = function () {
  43374. var camLeft = this._rigCameras[0];
  43375. var camRight = this._rigCameras[1];
  43376. switch (this.cameraRigMode) {
  43377. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43378. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43379. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43380. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43381. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43382. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43383. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43384. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43385. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43386. camLeft.setTarget(this.getTarget());
  43387. camRight.setTarget(this.getTarget());
  43388. break;
  43389. case BABYLON.Camera.RIG_MODE_VR:
  43390. if (camLeft.rotationQuaternion) {
  43391. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43392. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43393. }
  43394. else {
  43395. camLeft.rotation.copyFrom(this.rotation);
  43396. camRight.rotation.copyFrom(this.rotation);
  43397. }
  43398. camLeft.position.copyFrom(this.position);
  43399. camRight.position.copyFrom(this.position);
  43400. break;
  43401. }
  43402. _super.prototype._updateRigCameras.call(this);
  43403. };
  43404. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43405. if (!this._rigCamTransformMatrix) {
  43406. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43407. }
  43408. var target = this.getTarget();
  43409. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43410. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43411. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43412. };
  43413. TargetCamera.prototype.getClassName = function () {
  43414. return "TargetCamera";
  43415. };
  43416. __decorate([
  43417. BABYLON.serializeAsVector3()
  43418. ], TargetCamera.prototype, "rotation", void 0);
  43419. __decorate([
  43420. BABYLON.serialize()
  43421. ], TargetCamera.prototype, "speed", void 0);
  43422. __decorate([
  43423. BABYLON.serializeAsMeshReference("lockedTargetId")
  43424. ], TargetCamera.prototype, "lockedTarget", void 0);
  43425. return TargetCamera;
  43426. }(BABYLON.Camera));
  43427. BABYLON.TargetCamera = TargetCamera;
  43428. })(BABYLON || (BABYLON = {}));
  43429. //# sourceMappingURL=babylon.targetCamera.js.map
  43430. var BABYLON;
  43431. (function (BABYLON) {
  43432. var FreeCameraMouseInput = /** @class */ (function () {
  43433. function FreeCameraMouseInput(touchEnabled) {
  43434. if (touchEnabled === void 0) { touchEnabled = true; }
  43435. this.touchEnabled = touchEnabled;
  43436. this.buttons = [0, 1, 2];
  43437. this.angularSensibility = 2000.0;
  43438. this.previousPosition = null;
  43439. }
  43440. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43441. var _this = this;
  43442. var engine = this.camera.getEngine();
  43443. if (!this._pointerInput) {
  43444. this._pointerInput = function (p, s) {
  43445. var evt = p.event;
  43446. if (engine.isInVRExclusivePointerMode) {
  43447. return;
  43448. }
  43449. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43450. return;
  43451. }
  43452. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43453. return;
  43454. }
  43455. var srcElement = (evt.srcElement || evt.target);
  43456. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43457. try {
  43458. srcElement.setPointerCapture(evt.pointerId);
  43459. }
  43460. catch (e) {
  43461. //Nothing to do with the error. Execution will continue.
  43462. }
  43463. _this.previousPosition = {
  43464. x: evt.clientX,
  43465. y: evt.clientY
  43466. };
  43467. if (!noPreventDefault) {
  43468. evt.preventDefault();
  43469. element.focus();
  43470. }
  43471. }
  43472. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43473. try {
  43474. srcElement.releasePointerCapture(evt.pointerId);
  43475. }
  43476. catch (e) {
  43477. //Nothing to do with the error.
  43478. }
  43479. _this.previousPosition = null;
  43480. if (!noPreventDefault) {
  43481. evt.preventDefault();
  43482. }
  43483. }
  43484. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43485. if (!_this.previousPosition || engine.isPointerLock) {
  43486. return;
  43487. }
  43488. var offsetX = evt.clientX - _this.previousPosition.x;
  43489. var offsetY = evt.clientY - _this.previousPosition.y;
  43490. if (_this.camera.getScene().useRightHandedSystem) {
  43491. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43492. }
  43493. else {
  43494. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43495. }
  43496. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43497. _this.previousPosition = {
  43498. x: evt.clientX,
  43499. y: evt.clientY
  43500. };
  43501. if (!noPreventDefault) {
  43502. evt.preventDefault();
  43503. }
  43504. }
  43505. };
  43506. }
  43507. this._onMouseMove = function (evt) {
  43508. if (!engine.isPointerLock) {
  43509. return;
  43510. }
  43511. if (engine.isInVRExclusivePointerMode) {
  43512. return;
  43513. }
  43514. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43515. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43516. if (_this.camera.getScene().useRightHandedSystem) {
  43517. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43518. }
  43519. else {
  43520. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43521. }
  43522. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43523. _this.previousPosition = null;
  43524. if (!noPreventDefault) {
  43525. evt.preventDefault();
  43526. }
  43527. };
  43528. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43529. element.addEventListener("mousemove", this._onMouseMove, false);
  43530. };
  43531. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43532. if (this._observer && element) {
  43533. this.camera.getScene().onPointerObservable.remove(this._observer);
  43534. if (this._onMouseMove) {
  43535. element.removeEventListener("mousemove", this._onMouseMove);
  43536. }
  43537. this._observer = null;
  43538. this._onMouseMove = null;
  43539. this.previousPosition = null;
  43540. }
  43541. };
  43542. FreeCameraMouseInput.prototype.getClassName = function () {
  43543. return "FreeCameraMouseInput";
  43544. };
  43545. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43546. return "mouse";
  43547. };
  43548. __decorate([
  43549. BABYLON.serialize()
  43550. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43551. __decorate([
  43552. BABYLON.serialize()
  43553. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43554. return FreeCameraMouseInput;
  43555. }());
  43556. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43557. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43558. })(BABYLON || (BABYLON = {}));
  43559. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43560. var BABYLON;
  43561. (function (BABYLON) {
  43562. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43563. function FreeCameraKeyboardMoveInput() {
  43564. this._keys = new Array();
  43565. this.keysUp = [38];
  43566. this.keysDown = [40];
  43567. this.keysLeft = [37];
  43568. this.keysRight = [39];
  43569. }
  43570. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43571. var _this = this;
  43572. if (this._onCanvasBlurObserver) {
  43573. return;
  43574. }
  43575. this._scene = this.camera.getScene();
  43576. this._engine = this._scene.getEngine();
  43577. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43578. _this._keys = [];
  43579. });
  43580. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43581. var evt = info.event;
  43582. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43583. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43584. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43585. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43586. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43587. var index = _this._keys.indexOf(evt.keyCode);
  43588. if (index === -1) {
  43589. _this._keys.push(evt.keyCode);
  43590. }
  43591. if (!noPreventDefault) {
  43592. evt.preventDefault();
  43593. }
  43594. }
  43595. }
  43596. else {
  43597. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43598. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43599. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43600. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43601. var index = _this._keys.indexOf(evt.keyCode);
  43602. if (index >= 0) {
  43603. _this._keys.splice(index, 1);
  43604. }
  43605. if (!noPreventDefault) {
  43606. evt.preventDefault();
  43607. }
  43608. }
  43609. }
  43610. });
  43611. };
  43612. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43613. if (this._scene) {
  43614. if (this._onKeyboardObserver) {
  43615. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43616. }
  43617. if (this._onCanvasBlurObserver) {
  43618. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43619. }
  43620. this._onKeyboardObserver = null;
  43621. this._onCanvasBlurObserver = null;
  43622. }
  43623. this._keys = [];
  43624. };
  43625. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43626. if (this._onKeyboardObserver) {
  43627. var camera = this.camera;
  43628. // Keyboard
  43629. for (var index = 0; index < this._keys.length; index++) {
  43630. var keyCode = this._keys[index];
  43631. var speed = camera._computeLocalCameraSpeed();
  43632. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43633. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43634. }
  43635. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43636. camera._localDirection.copyFromFloats(0, 0, speed);
  43637. }
  43638. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43639. camera._localDirection.copyFromFloats(speed, 0, 0);
  43640. }
  43641. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43642. camera._localDirection.copyFromFloats(0, 0, -speed);
  43643. }
  43644. if (camera.getScene().useRightHandedSystem) {
  43645. camera._localDirection.z *= -1;
  43646. }
  43647. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43648. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43649. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43650. }
  43651. }
  43652. };
  43653. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43654. return "FreeCameraKeyboardMoveInput";
  43655. };
  43656. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43657. this._keys = [];
  43658. };
  43659. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43660. return "keyboard";
  43661. };
  43662. __decorate([
  43663. BABYLON.serialize()
  43664. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43665. __decorate([
  43666. BABYLON.serialize()
  43667. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43668. __decorate([
  43669. BABYLON.serialize()
  43670. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43671. __decorate([
  43672. BABYLON.serialize()
  43673. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43674. return FreeCameraKeyboardMoveInput;
  43675. }());
  43676. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43677. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43678. })(BABYLON || (BABYLON = {}));
  43679. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43680. var BABYLON;
  43681. (function (BABYLON) {
  43682. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43683. __extends(FreeCameraInputsManager, _super);
  43684. function FreeCameraInputsManager(camera) {
  43685. return _super.call(this, camera) || this;
  43686. }
  43687. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43688. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43689. return this;
  43690. };
  43691. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43692. if (touchEnabled === void 0) { touchEnabled = true; }
  43693. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43694. return this;
  43695. };
  43696. FreeCameraInputsManager.prototype.addGamepad = function () {
  43697. this.add(new BABYLON.FreeCameraGamepadInput());
  43698. return this;
  43699. };
  43700. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43701. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43702. return this;
  43703. };
  43704. FreeCameraInputsManager.prototype.addTouch = function () {
  43705. this.add(new BABYLON.FreeCameraTouchInput());
  43706. return this;
  43707. };
  43708. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43709. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43710. return this;
  43711. };
  43712. return FreeCameraInputsManager;
  43713. }(BABYLON.CameraInputsManager));
  43714. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43715. })(BABYLON || (BABYLON = {}));
  43716. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43717. var BABYLON;
  43718. (function (BABYLON) {
  43719. var FreeCamera = /** @class */ (function (_super) {
  43720. __extends(FreeCamera, _super);
  43721. function FreeCamera(name, position, scene) {
  43722. var _this = _super.call(this, name, position, scene) || this;
  43723. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43724. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43725. _this.checkCollisions = false;
  43726. _this.applyGravity = false;
  43727. _this._needMoveForGravity = false;
  43728. _this._oldPosition = BABYLON.Vector3.Zero();
  43729. _this._diffPosition = BABYLON.Vector3.Zero();
  43730. _this._newPosition = BABYLON.Vector3.Zero();
  43731. // Collisions
  43732. _this._collisionMask = -1;
  43733. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43734. if (collidedMesh === void 0) { collidedMesh = null; }
  43735. //TODO move this to the collision coordinator!
  43736. if (_this.getScene().workerCollisions)
  43737. newPosition.multiplyInPlace(_this._collider._radius);
  43738. var updatePosition = function (newPos) {
  43739. _this._newPosition.copyFrom(newPos);
  43740. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43741. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43742. _this.position.addInPlace(_this._diffPosition);
  43743. if (_this.onCollide && collidedMesh) {
  43744. _this.onCollide(collidedMesh);
  43745. }
  43746. }
  43747. };
  43748. updatePosition(newPosition);
  43749. };
  43750. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43751. _this.inputs.addKeyboard().addMouse();
  43752. return _this;
  43753. }
  43754. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43755. //-- begin properties for backward compatibility for inputs
  43756. /**
  43757. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43758. * Higher values reduce sensitivity.
  43759. */
  43760. get: function () {
  43761. var mouse = this.inputs.attached["mouse"];
  43762. if (mouse)
  43763. return mouse.angularSensibility;
  43764. return 0;
  43765. },
  43766. /**
  43767. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43768. * Higher values reduce sensitivity.
  43769. */
  43770. set: function (value) {
  43771. var mouse = this.inputs.attached["mouse"];
  43772. if (mouse)
  43773. mouse.angularSensibility = value;
  43774. },
  43775. enumerable: true,
  43776. configurable: true
  43777. });
  43778. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43779. get: function () {
  43780. var keyboard = this.inputs.attached["keyboard"];
  43781. if (keyboard)
  43782. return keyboard.keysUp;
  43783. return [];
  43784. },
  43785. set: function (value) {
  43786. var keyboard = this.inputs.attached["keyboard"];
  43787. if (keyboard)
  43788. keyboard.keysUp = value;
  43789. },
  43790. enumerable: true,
  43791. configurable: true
  43792. });
  43793. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43794. get: function () {
  43795. var keyboard = this.inputs.attached["keyboard"];
  43796. if (keyboard)
  43797. return keyboard.keysDown;
  43798. return [];
  43799. },
  43800. set: function (value) {
  43801. var keyboard = this.inputs.attached["keyboard"];
  43802. if (keyboard)
  43803. keyboard.keysDown = value;
  43804. },
  43805. enumerable: true,
  43806. configurable: true
  43807. });
  43808. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43809. get: function () {
  43810. var keyboard = this.inputs.attached["keyboard"];
  43811. if (keyboard)
  43812. return keyboard.keysLeft;
  43813. return [];
  43814. },
  43815. set: function (value) {
  43816. var keyboard = this.inputs.attached["keyboard"];
  43817. if (keyboard)
  43818. keyboard.keysLeft = value;
  43819. },
  43820. enumerable: true,
  43821. configurable: true
  43822. });
  43823. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43824. get: function () {
  43825. var keyboard = this.inputs.attached["keyboard"];
  43826. if (keyboard)
  43827. return keyboard.keysRight;
  43828. return [];
  43829. },
  43830. set: function (value) {
  43831. var keyboard = this.inputs.attached["keyboard"];
  43832. if (keyboard)
  43833. keyboard.keysRight = value;
  43834. },
  43835. enumerable: true,
  43836. configurable: true
  43837. });
  43838. // Controls
  43839. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43840. this.inputs.attachElement(element, noPreventDefault);
  43841. };
  43842. FreeCamera.prototype.detachControl = function (element) {
  43843. this.inputs.detachElement(element);
  43844. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43845. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43846. };
  43847. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43848. get: function () {
  43849. return this._collisionMask;
  43850. },
  43851. set: function (mask) {
  43852. this._collisionMask = !isNaN(mask) ? mask : -1;
  43853. },
  43854. enumerable: true,
  43855. configurable: true
  43856. });
  43857. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43858. var globalPosition;
  43859. if (this.parent) {
  43860. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43861. }
  43862. else {
  43863. globalPosition = this.position;
  43864. }
  43865. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43866. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43867. if (!this._collider) {
  43868. this._collider = new BABYLON.Collider();
  43869. }
  43870. this._collider._radius = this.ellipsoid;
  43871. this._collider.collisionMask = this._collisionMask;
  43872. //no need for clone, as long as gravity is not on.
  43873. var actualDisplacement = displacement;
  43874. //add gravity to the direction to prevent the dual-collision checking
  43875. if (this.applyGravity) {
  43876. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43877. actualDisplacement = displacement.add(this.getScene().gravity);
  43878. }
  43879. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43880. };
  43881. FreeCamera.prototype._checkInputs = function () {
  43882. if (!this._localDirection) {
  43883. this._localDirection = BABYLON.Vector3.Zero();
  43884. this._transformedDirection = BABYLON.Vector3.Zero();
  43885. }
  43886. this.inputs.checkInputs();
  43887. _super.prototype._checkInputs.call(this);
  43888. };
  43889. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43890. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43891. };
  43892. FreeCamera.prototype._updatePosition = function () {
  43893. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43894. this._collideWithWorld(this.cameraDirection);
  43895. }
  43896. else {
  43897. _super.prototype._updatePosition.call(this);
  43898. }
  43899. };
  43900. FreeCamera.prototype.dispose = function () {
  43901. this.inputs.clear();
  43902. _super.prototype.dispose.call(this);
  43903. };
  43904. FreeCamera.prototype.getClassName = function () {
  43905. return "FreeCamera";
  43906. };
  43907. __decorate([
  43908. BABYLON.serializeAsVector3()
  43909. ], FreeCamera.prototype, "ellipsoid", void 0);
  43910. __decorate([
  43911. BABYLON.serializeAsVector3()
  43912. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43913. __decorate([
  43914. BABYLON.serialize()
  43915. ], FreeCamera.prototype, "checkCollisions", void 0);
  43916. __decorate([
  43917. BABYLON.serialize()
  43918. ], FreeCamera.prototype, "applyGravity", void 0);
  43919. return FreeCamera;
  43920. }(BABYLON.TargetCamera));
  43921. BABYLON.FreeCamera = FreeCamera;
  43922. })(BABYLON || (BABYLON = {}));
  43923. //# sourceMappingURL=babylon.freeCamera.js.map
  43924. var BABYLON;
  43925. (function (BABYLON) {
  43926. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43927. function ArcRotateCameraKeyboardMoveInput() {
  43928. this._keys = new Array();
  43929. this.keysUp = [38];
  43930. this.keysDown = [40];
  43931. this.keysLeft = [37];
  43932. this.keysRight = [39];
  43933. this.keysReset = [220];
  43934. this.panningSensibility = 50.0;
  43935. this.zoomingSensibility = 25.0;
  43936. this.useAltToZoom = true;
  43937. }
  43938. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43939. var _this = this;
  43940. if (this._onCanvasBlurObserver) {
  43941. return;
  43942. }
  43943. this._scene = this.camera.getScene();
  43944. this._engine = this._scene.getEngine();
  43945. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43946. _this._keys = [];
  43947. });
  43948. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43949. var evt = info.event;
  43950. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43951. _this._ctrlPressed = evt.ctrlKey;
  43952. _this._altPressed = evt.altKey;
  43953. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43954. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43955. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43956. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43957. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43958. var index = _this._keys.indexOf(evt.keyCode);
  43959. if (index === -1) {
  43960. _this._keys.push(evt.keyCode);
  43961. }
  43962. if (evt.preventDefault) {
  43963. if (!noPreventDefault) {
  43964. evt.preventDefault();
  43965. }
  43966. }
  43967. }
  43968. }
  43969. else {
  43970. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43971. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43972. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43973. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43974. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43975. var index = _this._keys.indexOf(evt.keyCode);
  43976. if (index >= 0) {
  43977. _this._keys.splice(index, 1);
  43978. }
  43979. if (evt.preventDefault) {
  43980. if (!noPreventDefault) {
  43981. evt.preventDefault();
  43982. }
  43983. }
  43984. }
  43985. }
  43986. });
  43987. };
  43988. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43989. if (this._scene) {
  43990. if (this._onKeyboardObserver) {
  43991. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43992. }
  43993. if (this._onCanvasBlurObserver) {
  43994. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43995. }
  43996. this._onKeyboardObserver = null;
  43997. this._onCanvasBlurObserver = null;
  43998. }
  43999. this._keys = [];
  44000. };
  44001. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44002. if (this._onKeyboardObserver) {
  44003. var camera = this.camera;
  44004. for (var index = 0; index < this._keys.length; index++) {
  44005. var keyCode = this._keys[index];
  44006. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44007. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44008. camera.inertialPanningX -= 1 / this.panningSensibility;
  44009. }
  44010. else {
  44011. camera.inertialAlphaOffset -= 0.01;
  44012. }
  44013. }
  44014. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44015. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44016. camera.inertialPanningY += 1 / this.panningSensibility;
  44017. }
  44018. else if (this._altPressed && this.useAltToZoom) {
  44019. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44020. }
  44021. else {
  44022. camera.inertialBetaOffset -= 0.01;
  44023. }
  44024. }
  44025. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44026. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44027. camera.inertialPanningX += 1 / this.panningSensibility;
  44028. }
  44029. else {
  44030. camera.inertialAlphaOffset += 0.01;
  44031. }
  44032. }
  44033. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44034. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44035. camera.inertialPanningY -= 1 / this.panningSensibility;
  44036. }
  44037. else if (this._altPressed && this.useAltToZoom) {
  44038. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44039. }
  44040. else {
  44041. camera.inertialBetaOffset += 0.01;
  44042. }
  44043. }
  44044. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44045. camera.restoreState();
  44046. }
  44047. }
  44048. }
  44049. };
  44050. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44051. return "ArcRotateCameraKeyboardMoveInput";
  44052. };
  44053. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44054. return "keyboard";
  44055. };
  44056. __decorate([
  44057. BABYLON.serialize()
  44058. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44059. __decorate([
  44060. BABYLON.serialize()
  44061. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44062. __decorate([
  44063. BABYLON.serialize()
  44064. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44065. __decorate([
  44066. BABYLON.serialize()
  44067. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44068. __decorate([
  44069. BABYLON.serialize()
  44070. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44071. __decorate([
  44072. BABYLON.serialize()
  44073. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44074. __decorate([
  44075. BABYLON.serialize()
  44076. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44077. __decorate([
  44078. BABYLON.serialize()
  44079. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44080. return ArcRotateCameraKeyboardMoveInput;
  44081. }());
  44082. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44083. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44084. })(BABYLON || (BABYLON = {}));
  44085. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44086. var BABYLON;
  44087. (function (BABYLON) {
  44088. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44089. function ArcRotateCameraMouseWheelInput() {
  44090. this.wheelPrecision = 3.0;
  44091. /**
  44092. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44093. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44094. */
  44095. this.wheelDeltaPercentage = 0;
  44096. }
  44097. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44098. var _this = this;
  44099. this._wheel = function (p, s) {
  44100. //sanity check - this should be a PointerWheel event.
  44101. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44102. return;
  44103. var event = p.event;
  44104. var delta = 0;
  44105. if (event.wheelDelta) {
  44106. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44107. }
  44108. else if (event.detail) {
  44109. delta = -event.detail / _this.wheelPrecision;
  44110. }
  44111. if (delta)
  44112. _this.camera.inertialRadiusOffset += delta;
  44113. if (event.preventDefault) {
  44114. if (!noPreventDefault) {
  44115. event.preventDefault();
  44116. }
  44117. }
  44118. };
  44119. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44120. };
  44121. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44122. if (this._observer && element) {
  44123. this.camera.getScene().onPointerObservable.remove(this._observer);
  44124. this._observer = null;
  44125. this._wheel = null;
  44126. }
  44127. };
  44128. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44129. return "ArcRotateCameraMouseWheelInput";
  44130. };
  44131. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44132. return "mousewheel";
  44133. };
  44134. __decorate([
  44135. BABYLON.serialize()
  44136. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44137. __decorate([
  44138. BABYLON.serialize()
  44139. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44140. return ArcRotateCameraMouseWheelInput;
  44141. }());
  44142. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44143. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44144. })(BABYLON || (BABYLON = {}));
  44145. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44146. var BABYLON;
  44147. (function (BABYLON) {
  44148. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44149. function ArcRotateCameraPointersInput() {
  44150. this.buttons = [0, 1, 2];
  44151. this.angularSensibilityX = 1000.0;
  44152. this.angularSensibilityY = 1000.0;
  44153. this.pinchPrecision = 12.0;
  44154. /**
  44155. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44156. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44157. */
  44158. this.pinchDeltaPercentage = 0;
  44159. this.panningSensibility = 1000.0;
  44160. this.multiTouchPanning = true;
  44161. this.multiTouchPanAndZoom = true;
  44162. this._isPanClick = false;
  44163. this.pinchInwards = true;
  44164. }
  44165. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44166. var _this = this;
  44167. var engine = this.camera.getEngine();
  44168. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44169. var pointA = null;
  44170. var pointB = null;
  44171. var previousPinchSquaredDistance = 0;
  44172. var initialDistance = 0;
  44173. var twoFingerActivityCount = 0;
  44174. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44175. this._pointerInput = function (p, s) {
  44176. var evt = p.event;
  44177. var isTouch = p.event.pointerType === "touch";
  44178. if (engine.isInVRExclusivePointerMode) {
  44179. return;
  44180. }
  44181. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44182. return;
  44183. }
  44184. var srcElement = (evt.srcElement || evt.target);
  44185. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44186. try {
  44187. srcElement.setPointerCapture(evt.pointerId);
  44188. }
  44189. catch (e) {
  44190. //Nothing to do with the error. Execution will continue.
  44191. }
  44192. // Manage panning with pan button click
  44193. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44194. // manage pointers
  44195. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44196. if (pointA === null) {
  44197. pointA = cacheSoloPointer;
  44198. }
  44199. else if (pointB === null) {
  44200. pointB = cacheSoloPointer;
  44201. }
  44202. if (!noPreventDefault) {
  44203. evt.preventDefault();
  44204. element.focus();
  44205. }
  44206. }
  44207. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44208. _this.camera.restoreState();
  44209. }
  44210. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44211. try {
  44212. srcElement.releasePointerCapture(evt.pointerId);
  44213. }
  44214. catch (e) {
  44215. //Nothing to do with the error.
  44216. }
  44217. cacheSoloPointer = null;
  44218. previousPinchSquaredDistance = 0;
  44219. previousMultiTouchPanPosition.isPaning = false;
  44220. previousMultiTouchPanPosition.isPinching = false;
  44221. twoFingerActivityCount = 0;
  44222. initialDistance = 0;
  44223. if (!isTouch) {
  44224. pointB = null; // Mouse and pen are mono pointer
  44225. }
  44226. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44227. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44228. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44229. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44230. if (engine.badOS) {
  44231. pointA = pointB = null;
  44232. }
  44233. else {
  44234. //only remove the impacted pointer in case of multitouch allowing on most
  44235. //platforms switching from rotate to zoom and pan seamlessly.
  44236. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44237. pointA = pointB;
  44238. pointB = null;
  44239. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44240. }
  44241. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44242. pointB = null;
  44243. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44244. }
  44245. else {
  44246. pointA = pointB = null;
  44247. }
  44248. }
  44249. if (!noPreventDefault) {
  44250. evt.preventDefault();
  44251. }
  44252. }
  44253. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44254. if (!noPreventDefault) {
  44255. evt.preventDefault();
  44256. }
  44257. // One button down
  44258. if (pointA && pointB === null && cacheSoloPointer) {
  44259. if (_this.panningSensibility !== 0 &&
  44260. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44261. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44262. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44263. }
  44264. else {
  44265. var offsetX = evt.clientX - cacheSoloPointer.x;
  44266. var offsetY = evt.clientY - cacheSoloPointer.y;
  44267. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44268. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44269. }
  44270. cacheSoloPointer.x = evt.clientX;
  44271. cacheSoloPointer.y = evt.clientY;
  44272. }
  44273. else if (pointA && pointB) {
  44274. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44275. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44276. ed.x = evt.clientX;
  44277. ed.y = evt.clientY;
  44278. var direction = _this.pinchInwards ? 1 : -1;
  44279. var distX = pointA.x - pointB.x;
  44280. var distY = pointA.y - pointB.y;
  44281. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44282. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44283. if (previousPinchSquaredDistance === 0) {
  44284. initialDistance = pinchDistance;
  44285. previousPinchSquaredDistance = pinchSquaredDistance;
  44286. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44287. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44288. return;
  44289. }
  44290. if (_this.multiTouchPanAndZoom) {
  44291. if (_this.pinchDeltaPercentage) {
  44292. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44293. }
  44294. else {
  44295. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44296. (_this.pinchPrecision *
  44297. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44298. direction);
  44299. }
  44300. if (_this.panningSensibility !== 0) {
  44301. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44302. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44303. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44304. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44305. previousMultiTouchPanPosition.x = pointersCenterX;
  44306. previousMultiTouchPanPosition.y = pointersCenterY;
  44307. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44308. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44309. }
  44310. }
  44311. else {
  44312. twoFingerActivityCount++;
  44313. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44314. if (_this.pinchDeltaPercentage) {
  44315. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44316. }
  44317. else {
  44318. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44319. (_this.pinchPrecision *
  44320. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44321. direction);
  44322. }
  44323. previousMultiTouchPanPosition.isPaning = false;
  44324. previousMultiTouchPanPosition.isPinching = true;
  44325. }
  44326. else {
  44327. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44328. if (!previousMultiTouchPanPosition.isPaning) {
  44329. previousMultiTouchPanPosition.isPaning = true;
  44330. previousMultiTouchPanPosition.isPinching = false;
  44331. previousMultiTouchPanPosition.x = ed.x;
  44332. previousMultiTouchPanPosition.y = ed.y;
  44333. return;
  44334. }
  44335. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44336. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44337. }
  44338. }
  44339. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44340. previousMultiTouchPanPosition.x = ed.x;
  44341. previousMultiTouchPanPosition.y = ed.y;
  44342. }
  44343. }
  44344. previousPinchSquaredDistance = pinchSquaredDistance;
  44345. }
  44346. }
  44347. };
  44348. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44349. this._onContextMenu = function (evt) {
  44350. evt.preventDefault();
  44351. };
  44352. if (!this.camera._useCtrlForPanning) {
  44353. element.addEventListener("contextmenu", this._onContextMenu, false);
  44354. }
  44355. this._onLostFocus = function () {
  44356. //this._keys = [];
  44357. pointA = pointB = null;
  44358. previousPinchSquaredDistance = 0;
  44359. previousMultiTouchPanPosition.isPaning = false;
  44360. previousMultiTouchPanPosition.isPinching = false;
  44361. twoFingerActivityCount = 0;
  44362. cacheSoloPointer = null;
  44363. initialDistance = 0;
  44364. };
  44365. this._onMouseMove = function (evt) {
  44366. if (!engine.isPointerLock) {
  44367. return;
  44368. }
  44369. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44370. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44371. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44372. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44373. if (!noPreventDefault) {
  44374. evt.preventDefault();
  44375. }
  44376. };
  44377. this._onGestureStart = function (e) {
  44378. if (window.MSGesture === undefined) {
  44379. return;
  44380. }
  44381. if (!_this._MSGestureHandler) {
  44382. _this._MSGestureHandler = new MSGesture();
  44383. _this._MSGestureHandler.target = element;
  44384. }
  44385. _this._MSGestureHandler.addPointer(e.pointerId);
  44386. };
  44387. this._onGesture = function (e) {
  44388. _this.camera.radius *= e.scale;
  44389. if (e.preventDefault) {
  44390. if (!noPreventDefault) {
  44391. e.stopPropagation();
  44392. e.preventDefault();
  44393. }
  44394. }
  44395. };
  44396. element.addEventListener("mousemove", this._onMouseMove, false);
  44397. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44398. element.addEventListener("MSGestureChange", this._onGesture, false);
  44399. BABYLON.Tools.RegisterTopRootEvents([
  44400. { name: "blur", handler: this._onLostFocus }
  44401. ]);
  44402. };
  44403. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44404. if (this._onLostFocus) {
  44405. BABYLON.Tools.UnregisterTopRootEvents([
  44406. { name: "blur", handler: this._onLostFocus }
  44407. ]);
  44408. }
  44409. if (element && this._observer) {
  44410. this.camera.getScene().onPointerObservable.remove(this._observer);
  44411. this._observer = null;
  44412. if (this._onContextMenu) {
  44413. element.removeEventListener("contextmenu", this._onContextMenu);
  44414. }
  44415. if (this._onMouseMove) {
  44416. element.removeEventListener("mousemove", this._onMouseMove);
  44417. }
  44418. if (this._onGestureStart) {
  44419. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44420. }
  44421. if (this._onGesture) {
  44422. element.removeEventListener("MSGestureChange", this._onGesture);
  44423. }
  44424. this._isPanClick = false;
  44425. this.pinchInwards = true;
  44426. this._onMouseMove = null;
  44427. this._onGestureStart = null;
  44428. this._onGesture = null;
  44429. this._MSGestureHandler = null;
  44430. this._onLostFocus = null;
  44431. this._onContextMenu = null;
  44432. }
  44433. };
  44434. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44435. return "ArcRotateCameraPointersInput";
  44436. };
  44437. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44438. return "pointers";
  44439. };
  44440. __decorate([
  44441. BABYLON.serialize()
  44442. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44443. __decorate([
  44444. BABYLON.serialize()
  44445. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44446. __decorate([
  44447. BABYLON.serialize()
  44448. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44449. __decorate([
  44450. BABYLON.serialize()
  44451. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44452. __decorate([
  44453. BABYLON.serialize()
  44454. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44455. __decorate([
  44456. BABYLON.serialize()
  44457. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44458. __decorate([
  44459. BABYLON.serialize()
  44460. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44461. __decorate([
  44462. BABYLON.serialize()
  44463. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44464. return ArcRotateCameraPointersInput;
  44465. }());
  44466. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44467. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44468. })(BABYLON || (BABYLON = {}));
  44469. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44470. var BABYLON;
  44471. (function (BABYLON) {
  44472. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44473. __extends(ArcRotateCameraInputsManager, _super);
  44474. function ArcRotateCameraInputsManager(camera) {
  44475. return _super.call(this, camera) || this;
  44476. }
  44477. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44478. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44479. return this;
  44480. };
  44481. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44482. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44483. return this;
  44484. };
  44485. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44486. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44487. return this;
  44488. };
  44489. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44490. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44491. return this;
  44492. };
  44493. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44494. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44495. return this;
  44496. };
  44497. return ArcRotateCameraInputsManager;
  44498. }(BABYLON.CameraInputsManager));
  44499. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44500. })(BABYLON || (BABYLON = {}));
  44501. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44502. var BABYLON;
  44503. (function (BABYLON) {
  44504. var ArcRotateCamera = /** @class */ (function (_super) {
  44505. __extends(ArcRotateCamera, _super);
  44506. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44507. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44508. _this.inertialAlphaOffset = 0;
  44509. _this.inertialBetaOffset = 0;
  44510. _this.inertialRadiusOffset = 0;
  44511. _this.lowerAlphaLimit = null;
  44512. _this.upperAlphaLimit = null;
  44513. _this.lowerBetaLimit = 0.01;
  44514. _this.upperBetaLimit = Math.PI;
  44515. _this.lowerRadiusLimit = null;
  44516. _this.upperRadiusLimit = null;
  44517. _this.inertialPanningX = 0;
  44518. _this.inertialPanningY = 0;
  44519. _this.pinchToPanMaxDistance = 20;
  44520. _this.panningDistanceLimit = null;
  44521. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44522. _this.panningInertia = 0.9;
  44523. //-- end properties for backward compatibility for inputs
  44524. _this.zoomOnFactor = 1;
  44525. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44526. _this.allowUpsideDown = true;
  44527. _this._viewMatrix = new BABYLON.Matrix();
  44528. // Panning
  44529. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44530. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44531. _this.checkCollisions = false;
  44532. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44533. _this._previousPosition = BABYLON.Vector3.Zero();
  44534. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44535. _this._newPosition = BABYLON.Vector3.Zero();
  44536. _this._computationVector = BABYLON.Vector3.Zero();
  44537. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44538. if (collidedMesh === void 0) { collidedMesh = null; }
  44539. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44540. newPosition.multiplyInPlace(_this._collider._radius);
  44541. }
  44542. if (!collidedMesh) {
  44543. _this._previousPosition.copyFrom(_this.position);
  44544. }
  44545. else {
  44546. _this.setPosition(newPosition);
  44547. if (_this.onCollide) {
  44548. _this.onCollide(collidedMesh);
  44549. }
  44550. }
  44551. // Recompute because of constraints
  44552. var cosa = Math.cos(_this.alpha);
  44553. var sina = Math.sin(_this.alpha);
  44554. var cosb = Math.cos(_this.beta);
  44555. var sinb = Math.sin(_this.beta);
  44556. if (sinb === 0) {
  44557. sinb = 0.0001;
  44558. }
  44559. var target = _this._getTargetPosition();
  44560. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  44561. target.addToRef(_this._computationVector, _this._newPosition);
  44562. _this.position.copyFrom(_this._newPosition);
  44563. var up = _this.upVector;
  44564. if (_this.allowUpsideDown && _this.beta < 0) {
  44565. up = up.clone();
  44566. up = up.negate();
  44567. }
  44568. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44569. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44570. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44571. _this._collisionTriggered = false;
  44572. };
  44573. _this._target = BABYLON.Vector3.Zero();
  44574. if (target) {
  44575. _this.setTarget(target);
  44576. }
  44577. _this.alpha = alpha;
  44578. _this.beta = beta;
  44579. _this.radius = radius;
  44580. _this.getViewMatrix();
  44581. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44582. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44583. return _this;
  44584. }
  44585. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44586. get: function () {
  44587. return this._target;
  44588. },
  44589. set: function (value) {
  44590. this.setTarget(value);
  44591. },
  44592. enumerable: true,
  44593. configurable: true
  44594. });
  44595. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44596. //-- begin properties for backward compatibility for inputs
  44597. get: function () {
  44598. var pointers = this.inputs.attached["pointers"];
  44599. if (pointers)
  44600. return pointers.angularSensibilityX;
  44601. return 0;
  44602. },
  44603. set: function (value) {
  44604. var pointers = this.inputs.attached["pointers"];
  44605. if (pointers) {
  44606. pointers.angularSensibilityX = value;
  44607. }
  44608. },
  44609. enumerable: true,
  44610. configurable: true
  44611. });
  44612. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44613. get: function () {
  44614. var pointers = this.inputs.attached["pointers"];
  44615. if (pointers)
  44616. return pointers.angularSensibilityY;
  44617. return 0;
  44618. },
  44619. set: function (value) {
  44620. var pointers = this.inputs.attached["pointers"];
  44621. if (pointers) {
  44622. pointers.angularSensibilityY = value;
  44623. }
  44624. },
  44625. enumerable: true,
  44626. configurable: true
  44627. });
  44628. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44629. get: function () {
  44630. var pointers = this.inputs.attached["pointers"];
  44631. if (pointers)
  44632. return pointers.pinchPrecision;
  44633. return 0;
  44634. },
  44635. set: function (value) {
  44636. var pointers = this.inputs.attached["pointers"];
  44637. if (pointers) {
  44638. pointers.pinchPrecision = value;
  44639. }
  44640. },
  44641. enumerable: true,
  44642. configurable: true
  44643. });
  44644. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44645. get: function () {
  44646. var pointers = this.inputs.attached["pointers"];
  44647. if (pointers)
  44648. return pointers.pinchDeltaPercentage;
  44649. return 0;
  44650. },
  44651. set: function (value) {
  44652. var pointers = this.inputs.attached["pointers"];
  44653. if (pointers) {
  44654. pointers.pinchDeltaPercentage = value;
  44655. }
  44656. },
  44657. enumerable: true,
  44658. configurable: true
  44659. });
  44660. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44661. get: function () {
  44662. var pointers = this.inputs.attached["pointers"];
  44663. if (pointers)
  44664. return pointers.panningSensibility;
  44665. return 0;
  44666. },
  44667. set: function (value) {
  44668. var pointers = this.inputs.attached["pointers"];
  44669. if (pointers) {
  44670. pointers.panningSensibility = value;
  44671. }
  44672. },
  44673. enumerable: true,
  44674. configurable: true
  44675. });
  44676. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44677. get: function () {
  44678. var keyboard = this.inputs.attached["keyboard"];
  44679. if (keyboard)
  44680. return keyboard.keysUp;
  44681. return [];
  44682. },
  44683. set: function (value) {
  44684. var keyboard = this.inputs.attached["keyboard"];
  44685. if (keyboard)
  44686. keyboard.keysUp = value;
  44687. },
  44688. enumerable: true,
  44689. configurable: true
  44690. });
  44691. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44692. get: function () {
  44693. var keyboard = this.inputs.attached["keyboard"];
  44694. if (keyboard)
  44695. return keyboard.keysDown;
  44696. return [];
  44697. },
  44698. set: function (value) {
  44699. var keyboard = this.inputs.attached["keyboard"];
  44700. if (keyboard)
  44701. keyboard.keysDown = value;
  44702. },
  44703. enumerable: true,
  44704. configurable: true
  44705. });
  44706. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44707. get: function () {
  44708. var keyboard = this.inputs.attached["keyboard"];
  44709. if (keyboard)
  44710. return keyboard.keysLeft;
  44711. return [];
  44712. },
  44713. set: function (value) {
  44714. var keyboard = this.inputs.attached["keyboard"];
  44715. if (keyboard)
  44716. keyboard.keysLeft = value;
  44717. },
  44718. enumerable: true,
  44719. configurable: true
  44720. });
  44721. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44722. get: function () {
  44723. var keyboard = this.inputs.attached["keyboard"];
  44724. if (keyboard)
  44725. return keyboard.keysRight;
  44726. return [];
  44727. },
  44728. set: function (value) {
  44729. var keyboard = this.inputs.attached["keyboard"];
  44730. if (keyboard)
  44731. keyboard.keysRight = value;
  44732. },
  44733. enumerable: true,
  44734. configurable: true
  44735. });
  44736. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44737. get: function () {
  44738. var mousewheel = this.inputs.attached["mousewheel"];
  44739. if (mousewheel)
  44740. return mousewheel.wheelPrecision;
  44741. return 0;
  44742. },
  44743. set: function (value) {
  44744. var mousewheel = this.inputs.attached["mousewheel"];
  44745. if (mousewheel)
  44746. mousewheel.wheelPrecision = value;
  44747. },
  44748. enumerable: true,
  44749. configurable: true
  44750. });
  44751. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44752. get: function () {
  44753. var mousewheel = this.inputs.attached["mousewheel"];
  44754. if (mousewheel)
  44755. return mousewheel.wheelDeltaPercentage;
  44756. return 0;
  44757. },
  44758. set: function (value) {
  44759. var mousewheel = this.inputs.attached["mousewheel"];
  44760. if (mousewheel)
  44761. mousewheel.wheelDeltaPercentage = value;
  44762. },
  44763. enumerable: true,
  44764. configurable: true
  44765. });
  44766. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44767. get: function () {
  44768. return this._bouncingBehavior;
  44769. },
  44770. enumerable: true,
  44771. configurable: true
  44772. });
  44773. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44774. get: function () {
  44775. return this._bouncingBehavior != null;
  44776. },
  44777. set: function (value) {
  44778. if (value === this.useBouncingBehavior) {
  44779. return;
  44780. }
  44781. if (value) {
  44782. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44783. this.addBehavior(this._bouncingBehavior);
  44784. }
  44785. else if (this._bouncingBehavior) {
  44786. this.removeBehavior(this._bouncingBehavior);
  44787. this._bouncingBehavior = null;
  44788. }
  44789. },
  44790. enumerable: true,
  44791. configurable: true
  44792. });
  44793. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44794. get: function () {
  44795. return this._framingBehavior;
  44796. },
  44797. enumerable: true,
  44798. configurable: true
  44799. });
  44800. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44801. get: function () {
  44802. return this._framingBehavior != null;
  44803. },
  44804. set: function (value) {
  44805. if (value === this.useFramingBehavior) {
  44806. return;
  44807. }
  44808. if (value) {
  44809. this._framingBehavior = new BABYLON.FramingBehavior();
  44810. this.addBehavior(this._framingBehavior);
  44811. }
  44812. else if (this._framingBehavior) {
  44813. this.removeBehavior(this._framingBehavior);
  44814. this._framingBehavior = null;
  44815. }
  44816. },
  44817. enumerable: true,
  44818. configurable: true
  44819. });
  44820. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44821. get: function () {
  44822. return this._autoRotationBehavior;
  44823. },
  44824. enumerable: true,
  44825. configurable: true
  44826. });
  44827. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44828. get: function () {
  44829. return this._autoRotationBehavior != null;
  44830. },
  44831. set: function (value) {
  44832. if (value === this.useAutoRotationBehavior) {
  44833. return;
  44834. }
  44835. if (value) {
  44836. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44837. this.addBehavior(this._autoRotationBehavior);
  44838. }
  44839. else if (this._autoRotationBehavior) {
  44840. this.removeBehavior(this._autoRotationBehavior);
  44841. this._autoRotationBehavior = null;
  44842. }
  44843. },
  44844. enumerable: true,
  44845. configurable: true
  44846. });
  44847. // Cache
  44848. ArcRotateCamera.prototype._initCache = function () {
  44849. _super.prototype._initCache.call(this);
  44850. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44851. this._cache.alpha = undefined;
  44852. this._cache.beta = undefined;
  44853. this._cache.radius = undefined;
  44854. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44855. };
  44856. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44857. if (!ignoreParentClass) {
  44858. _super.prototype._updateCache.call(this);
  44859. }
  44860. this._cache._target.copyFrom(this._getTargetPosition());
  44861. this._cache.alpha = this.alpha;
  44862. this._cache.beta = this.beta;
  44863. this._cache.radius = this.radius;
  44864. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44865. };
  44866. ArcRotateCamera.prototype._getTargetPosition = function () {
  44867. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44868. var pos = this._targetHost.getAbsolutePosition();
  44869. if (this._targetBoundingCenter) {
  44870. pos.addToRef(this._targetBoundingCenter, this._target);
  44871. }
  44872. else {
  44873. this._target.copyFrom(pos);
  44874. }
  44875. }
  44876. var lockedTargetPosition = this._getLockedTargetPosition();
  44877. if (lockedTargetPosition) {
  44878. return lockedTargetPosition;
  44879. }
  44880. return this._target;
  44881. };
  44882. ArcRotateCamera.prototype.storeState = function () {
  44883. this._storedAlpha = this.alpha;
  44884. this._storedBeta = this.beta;
  44885. this._storedRadius = this.radius;
  44886. this._storedTarget = this._getTargetPosition().clone();
  44887. return _super.prototype.storeState.call(this);
  44888. };
  44889. /**
  44890. * Restored camera state. You must call storeState() first
  44891. */
  44892. ArcRotateCamera.prototype._restoreStateValues = function () {
  44893. if (!_super.prototype._restoreStateValues.call(this)) {
  44894. return false;
  44895. }
  44896. this.alpha = this._storedAlpha;
  44897. this.beta = this._storedBeta;
  44898. this.radius = this._storedRadius;
  44899. this.setTarget(this._storedTarget.clone());
  44900. this.inertialAlphaOffset = 0;
  44901. this.inertialBetaOffset = 0;
  44902. this.inertialRadiusOffset = 0;
  44903. this.inertialPanningX = 0;
  44904. this.inertialPanningY = 0;
  44905. return true;
  44906. };
  44907. // Synchronized
  44908. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44909. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44910. return false;
  44911. return this._cache._target.equals(this._getTargetPosition())
  44912. && this._cache.alpha === this.alpha
  44913. && this._cache.beta === this.beta
  44914. && this._cache.radius === this.radius
  44915. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44916. };
  44917. // Methods
  44918. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44919. var _this = this;
  44920. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44921. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44922. this._useCtrlForPanning = useCtrlForPanning;
  44923. this._panningMouseButton = panningMouseButton;
  44924. this.inputs.attachElement(element, noPreventDefault);
  44925. this._reset = function () {
  44926. _this.inertialAlphaOffset = 0;
  44927. _this.inertialBetaOffset = 0;
  44928. _this.inertialRadiusOffset = 0;
  44929. _this.inertialPanningX = 0;
  44930. _this.inertialPanningY = 0;
  44931. };
  44932. };
  44933. ArcRotateCamera.prototype.detachControl = function (element) {
  44934. this.inputs.detachElement(element);
  44935. if (this._reset) {
  44936. this._reset();
  44937. }
  44938. };
  44939. ArcRotateCamera.prototype._checkInputs = function () {
  44940. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44941. if (this._collisionTriggered) {
  44942. return;
  44943. }
  44944. this.inputs.checkInputs();
  44945. // Inertia
  44946. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44947. if (this.getScene().useRightHandedSystem) {
  44948. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44949. }
  44950. else {
  44951. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44952. }
  44953. this.beta += this.inertialBetaOffset;
  44954. this.radius -= this.inertialRadiusOffset;
  44955. this.inertialAlphaOffset *= this.inertia;
  44956. this.inertialBetaOffset *= this.inertia;
  44957. this.inertialRadiusOffset *= this.inertia;
  44958. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44959. this.inertialAlphaOffset = 0;
  44960. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44961. this.inertialBetaOffset = 0;
  44962. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44963. this.inertialRadiusOffset = 0;
  44964. }
  44965. // Panning inertia
  44966. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44967. if (!this._localDirection) {
  44968. this._localDirection = BABYLON.Vector3.Zero();
  44969. this._transformedDirection = BABYLON.Vector3.Zero();
  44970. }
  44971. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44972. this._localDirection.multiplyInPlace(this.panningAxis);
  44973. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44974. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44975. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44976. if (!this.panningAxis.y) {
  44977. this._transformedDirection.y = 0;
  44978. }
  44979. if (!this._targetHost) {
  44980. if (this.panningDistanceLimit) {
  44981. this._transformedDirection.addInPlace(this._target);
  44982. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44983. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44984. this._target.copyFrom(this._transformedDirection);
  44985. }
  44986. }
  44987. else {
  44988. this._target.addInPlace(this._transformedDirection);
  44989. }
  44990. }
  44991. this.inertialPanningX *= this.panningInertia;
  44992. this.inertialPanningY *= this.panningInertia;
  44993. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44994. this.inertialPanningX = 0;
  44995. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44996. this.inertialPanningY = 0;
  44997. }
  44998. // Limits
  44999. this._checkLimits();
  45000. _super.prototype._checkInputs.call(this);
  45001. };
  45002. ArcRotateCamera.prototype._checkLimits = function () {
  45003. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45004. if (this.allowUpsideDown && this.beta > Math.PI) {
  45005. this.beta = this.beta - (2 * Math.PI);
  45006. }
  45007. }
  45008. else {
  45009. if (this.beta < this.lowerBetaLimit) {
  45010. this.beta = this.lowerBetaLimit;
  45011. }
  45012. }
  45013. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45014. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45015. this.beta = this.beta + (2 * Math.PI);
  45016. }
  45017. }
  45018. else {
  45019. if (this.beta > this.upperBetaLimit) {
  45020. this.beta = this.upperBetaLimit;
  45021. }
  45022. }
  45023. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45024. this.alpha = this.lowerAlphaLimit;
  45025. }
  45026. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45027. this.alpha = this.upperAlphaLimit;
  45028. }
  45029. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45030. this.radius = this.lowerRadiusLimit;
  45031. }
  45032. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45033. this.radius = this.upperRadiusLimit;
  45034. }
  45035. };
  45036. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45037. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45038. this.radius = this._computationVector.length();
  45039. if (this.radius === 0) {
  45040. this.radius = 0.0001; // Just to avoid division by zero
  45041. }
  45042. // Alpha
  45043. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45044. if (this._computationVector.z < 0) {
  45045. this.alpha = 2 * Math.PI - this.alpha;
  45046. }
  45047. // Beta
  45048. this.beta = Math.acos(this._computationVector.y / this.radius);
  45049. this._checkLimits();
  45050. };
  45051. ArcRotateCamera.prototype.setPosition = function (position) {
  45052. if (this.position.equals(position)) {
  45053. return;
  45054. }
  45055. this.position.copyFrom(position);
  45056. this.rebuildAnglesAndRadius();
  45057. };
  45058. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45059. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45060. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45061. if (target.getBoundingInfo) {
  45062. if (toBoundingCenter) {
  45063. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45064. }
  45065. else {
  45066. this._targetBoundingCenter = null;
  45067. }
  45068. this._targetHost = target;
  45069. this._target = this._getTargetPosition();
  45070. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45071. }
  45072. else {
  45073. var newTarget = target;
  45074. var currentTarget = this._getTargetPosition();
  45075. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45076. return;
  45077. }
  45078. this._targetHost = null;
  45079. this._target = newTarget;
  45080. this._targetBoundingCenter = null;
  45081. this.onMeshTargetChangedObservable.notifyObservers(null);
  45082. }
  45083. this.rebuildAnglesAndRadius();
  45084. };
  45085. ArcRotateCamera.prototype._getViewMatrix = function () {
  45086. // Compute
  45087. var cosa = Math.cos(this.alpha);
  45088. var sina = Math.sin(this.alpha);
  45089. var cosb = Math.cos(this.beta);
  45090. var sinb = Math.sin(this.beta);
  45091. if (sinb === 0) {
  45092. sinb = 0.0001;
  45093. }
  45094. var target = this._getTargetPosition();
  45095. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45096. target.addToRef(this._computationVector, this._newPosition);
  45097. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45098. if (!this._collider) {
  45099. this._collider = new BABYLON.Collider();
  45100. }
  45101. this._collider._radius = this.collisionRadius;
  45102. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45103. this._collisionTriggered = true;
  45104. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45105. }
  45106. else {
  45107. this.position.copyFrom(this._newPosition);
  45108. var up = this.upVector;
  45109. if (this.allowUpsideDown && sinb < 0) {
  45110. up = up.clone();
  45111. up = up.negate();
  45112. }
  45113. if (this.getScene().useRightHandedSystem) {
  45114. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45115. }
  45116. else {
  45117. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45118. }
  45119. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45120. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45121. }
  45122. this._currentTarget = target;
  45123. return this._viewMatrix;
  45124. };
  45125. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45126. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45127. meshes = meshes || this.getScene().meshes;
  45128. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45129. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45130. this.radius = distance * this.zoomOnFactor;
  45131. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45132. };
  45133. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45134. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45135. var meshesOrMinMaxVector;
  45136. var distance;
  45137. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45138. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45139. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45140. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45141. }
  45142. else {
  45143. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45144. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45145. distance = minMaxVectorAndDistance.distance;
  45146. }
  45147. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45148. if (!doNotUpdateMaxZ) {
  45149. this.maxZ = distance * 2;
  45150. }
  45151. };
  45152. /**
  45153. * @override
  45154. * Override Camera.createRigCamera
  45155. */
  45156. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45157. var alphaShift = 0;
  45158. switch (this.cameraRigMode) {
  45159. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45160. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45161. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45162. case BABYLON.Camera.RIG_MODE_VR:
  45163. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45164. break;
  45165. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45166. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45167. break;
  45168. }
  45169. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45170. rigCam._cameraRigParams = {};
  45171. return rigCam;
  45172. };
  45173. /**
  45174. * @override
  45175. * Override Camera._updateRigCameras
  45176. */
  45177. ArcRotateCamera.prototype._updateRigCameras = function () {
  45178. var camLeft = this._rigCameras[0];
  45179. var camRight = this._rigCameras[1];
  45180. camLeft.beta = camRight.beta = this.beta;
  45181. camLeft.radius = camRight.radius = this.radius;
  45182. switch (this.cameraRigMode) {
  45183. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45184. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45185. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45186. case BABYLON.Camera.RIG_MODE_VR:
  45187. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45188. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45189. break;
  45190. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45191. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45192. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45193. break;
  45194. }
  45195. _super.prototype._updateRigCameras.call(this);
  45196. };
  45197. ArcRotateCamera.prototype.dispose = function () {
  45198. this.inputs.clear();
  45199. _super.prototype.dispose.call(this);
  45200. };
  45201. ArcRotateCamera.prototype.getClassName = function () {
  45202. return "ArcRotateCamera";
  45203. };
  45204. __decorate([
  45205. BABYLON.serialize()
  45206. ], ArcRotateCamera.prototype, "alpha", void 0);
  45207. __decorate([
  45208. BABYLON.serialize()
  45209. ], ArcRotateCamera.prototype, "beta", void 0);
  45210. __decorate([
  45211. BABYLON.serialize()
  45212. ], ArcRotateCamera.prototype, "radius", void 0);
  45213. __decorate([
  45214. BABYLON.serializeAsVector3("target")
  45215. ], ArcRotateCamera.prototype, "_target", void 0);
  45216. __decorate([
  45217. BABYLON.serialize()
  45218. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45219. __decorate([
  45220. BABYLON.serialize()
  45221. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45222. __decorate([
  45223. BABYLON.serialize()
  45224. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45225. __decorate([
  45226. BABYLON.serialize()
  45227. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45228. __decorate([
  45229. BABYLON.serialize()
  45230. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45231. __decorate([
  45232. BABYLON.serialize()
  45233. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45234. __decorate([
  45235. BABYLON.serialize()
  45236. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45237. __decorate([
  45238. BABYLON.serialize()
  45239. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45240. __decorate([
  45241. BABYLON.serialize()
  45242. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45243. __decorate([
  45244. BABYLON.serialize()
  45245. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45246. __decorate([
  45247. BABYLON.serialize()
  45248. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45249. __decorate([
  45250. BABYLON.serialize()
  45251. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45252. __decorate([
  45253. BABYLON.serialize()
  45254. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45255. __decorate([
  45256. BABYLON.serializeAsVector3()
  45257. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45258. __decorate([
  45259. BABYLON.serialize()
  45260. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45261. __decorate([
  45262. BABYLON.serialize()
  45263. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45264. __decorate([
  45265. BABYLON.serialize()
  45266. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45267. return ArcRotateCamera;
  45268. }(BABYLON.TargetCamera));
  45269. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45270. })(BABYLON || (BABYLON = {}));
  45271. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45272. var BABYLON;
  45273. (function (BABYLON) {
  45274. /**
  45275. * The HemisphericLight simulates the ambient environment light,
  45276. * so the passed direction is the light reflection direction, not the incoming direction.
  45277. */
  45278. var HemisphericLight = /** @class */ (function (_super) {
  45279. __extends(HemisphericLight, _super);
  45280. /**
  45281. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45282. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45283. * The HemisphericLight can't cast shadows.
  45284. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45285. * @param name The friendly name of the light
  45286. * @param direction The direction of the light reflection
  45287. * @param scene The scene the light belongs to
  45288. */
  45289. function HemisphericLight(name, direction, scene) {
  45290. var _this = _super.call(this, name, scene) || this;
  45291. /**
  45292. * The groundColor is the light in the opposite direction to the one specified during creation.
  45293. * 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.
  45294. */
  45295. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45296. _this.direction = direction || BABYLON.Vector3.Up();
  45297. return _this;
  45298. }
  45299. HemisphericLight.prototype._buildUniformLayout = function () {
  45300. this._uniformBuffer.addUniform("vLightData", 4);
  45301. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45302. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45303. this._uniformBuffer.addUniform("vLightGround", 3);
  45304. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45305. this._uniformBuffer.addUniform("depthValues", 2);
  45306. this._uniformBuffer.create();
  45307. };
  45308. /**
  45309. * Returns the string "HemisphericLight".
  45310. * @return The class name
  45311. */
  45312. HemisphericLight.prototype.getClassName = function () {
  45313. return "HemisphericLight";
  45314. };
  45315. /**
  45316. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45317. * Returns the updated direction.
  45318. * @param target The target the direction should point to
  45319. * @return The computed direction
  45320. */
  45321. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45322. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45323. return this.direction;
  45324. };
  45325. /**
  45326. * Returns the shadow generator associated to the light.
  45327. * @returns Always null for hemispheric lights because it does not support shadows.
  45328. */
  45329. HemisphericLight.prototype.getShadowGenerator = function () {
  45330. return null;
  45331. };
  45332. /**
  45333. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45334. * @param effect The effect to update
  45335. * @param lightIndex The index of the light in the effect to update
  45336. * @returns The hemispheric light
  45337. */
  45338. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45339. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45340. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45341. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45342. return this;
  45343. };
  45344. /**
  45345. * @ignore internal use only.
  45346. */
  45347. HemisphericLight.prototype._getWorldMatrix = function () {
  45348. if (!this._worldMatrix) {
  45349. this._worldMatrix = BABYLON.Matrix.Identity();
  45350. }
  45351. return this._worldMatrix;
  45352. };
  45353. /**
  45354. * Returns the integer 3.
  45355. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45356. */
  45357. HemisphericLight.prototype.getTypeID = function () {
  45358. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45359. };
  45360. __decorate([
  45361. BABYLON.serializeAsColor3()
  45362. ], HemisphericLight.prototype, "groundColor", void 0);
  45363. __decorate([
  45364. BABYLON.serializeAsVector3()
  45365. ], HemisphericLight.prototype, "direction", void 0);
  45366. return HemisphericLight;
  45367. }(BABYLON.Light));
  45368. BABYLON.HemisphericLight = HemisphericLight;
  45369. })(BABYLON || (BABYLON = {}));
  45370. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45371. var BABYLON;
  45372. (function (BABYLON) {
  45373. /**
  45374. * Base implementation of @see IShadowLight
  45375. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45376. */
  45377. var ShadowLight = /** @class */ (function (_super) {
  45378. __extends(ShadowLight, _super);
  45379. function ShadowLight() {
  45380. var _this = _super !== null && _super.apply(this, arguments) || this;
  45381. _this._needProjectionMatrixCompute = true;
  45382. return _this;
  45383. }
  45384. ShadowLight.prototype._setPosition = function (value) {
  45385. this._position = value;
  45386. };
  45387. Object.defineProperty(ShadowLight.prototype, "position", {
  45388. /**
  45389. * Sets the position the shadow will be casted from. Also use as the light position for both
  45390. * point and spot lights.
  45391. */
  45392. get: function () {
  45393. return this._position;
  45394. },
  45395. /**
  45396. * Sets the position the shadow will be casted from. Also use as the light position for both
  45397. * point and spot lights.
  45398. */
  45399. set: function (value) {
  45400. this._setPosition(value);
  45401. },
  45402. enumerable: true,
  45403. configurable: true
  45404. });
  45405. ShadowLight.prototype._setDirection = function (value) {
  45406. this._direction = value;
  45407. };
  45408. Object.defineProperty(ShadowLight.prototype, "direction", {
  45409. /**
  45410. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45411. * Also use as the light direction on spot and directional lights.
  45412. */
  45413. get: function () {
  45414. return this._direction;
  45415. },
  45416. /**
  45417. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45418. * Also use as the light direction on spot and directional lights.
  45419. */
  45420. set: function (value) {
  45421. this._setDirection(value);
  45422. },
  45423. enumerable: true,
  45424. configurable: true
  45425. });
  45426. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45427. /**
  45428. * Gets the shadow projection clipping minimum z value.
  45429. */
  45430. get: function () {
  45431. return this._shadowMinZ;
  45432. },
  45433. /**
  45434. * Sets the shadow projection clipping minimum z value.
  45435. */
  45436. set: function (value) {
  45437. this._shadowMinZ = value;
  45438. this.forceProjectionMatrixCompute();
  45439. },
  45440. enumerable: true,
  45441. configurable: true
  45442. });
  45443. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45444. /**
  45445. * Sets the shadow projection clipping maximum z value.
  45446. */
  45447. get: function () {
  45448. return this._shadowMaxZ;
  45449. },
  45450. /**
  45451. * Gets the shadow projection clipping maximum z value.
  45452. */
  45453. set: function (value) {
  45454. this._shadowMaxZ = value;
  45455. this.forceProjectionMatrixCompute();
  45456. },
  45457. enumerable: true,
  45458. configurable: true
  45459. });
  45460. /**
  45461. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45462. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45463. */
  45464. ShadowLight.prototype.computeTransformedInformation = function () {
  45465. if (this.parent && this.parent.getWorldMatrix) {
  45466. if (!this.transformedPosition) {
  45467. this.transformedPosition = BABYLON.Vector3.Zero();
  45468. }
  45469. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45470. // In case the direction is present.
  45471. if (this.direction) {
  45472. if (!this.transformedDirection) {
  45473. this.transformedDirection = BABYLON.Vector3.Zero();
  45474. }
  45475. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45476. }
  45477. return true;
  45478. }
  45479. return false;
  45480. };
  45481. /**
  45482. * Return the depth scale used for the shadow map.
  45483. * @returns the depth scale.
  45484. */
  45485. ShadowLight.prototype.getDepthScale = function () {
  45486. return 50.0;
  45487. };
  45488. /**
  45489. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45490. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45491. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45492. */
  45493. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45494. return this.transformedDirection ? this.transformedDirection : this.direction;
  45495. };
  45496. /**
  45497. * Returns the ShadowLight absolute position in the World.
  45498. * @returns the position vector in world space
  45499. */
  45500. ShadowLight.prototype.getAbsolutePosition = function () {
  45501. return this.transformedPosition ? this.transformedPosition : this.position;
  45502. };
  45503. /**
  45504. * Sets the ShadowLight direction toward the passed target.
  45505. * @param target The point tot target in local space
  45506. * @returns the updated ShadowLight direction
  45507. */
  45508. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45509. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45510. return this.direction;
  45511. };
  45512. /**
  45513. * Returns the light rotation in euler definition.
  45514. * @returns the x y z rotation in local space.
  45515. */
  45516. ShadowLight.prototype.getRotation = function () {
  45517. this.direction.normalize();
  45518. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45519. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45520. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45521. };
  45522. /**
  45523. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45524. * @returns true if a cube texture needs to be use
  45525. */
  45526. ShadowLight.prototype.needCube = function () {
  45527. return false;
  45528. };
  45529. /**
  45530. * Detects if the projection matrix requires to be recomputed this frame.
  45531. * @returns true if it requires to be recomputed otherwise, false.
  45532. */
  45533. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45534. return this._needProjectionMatrixCompute;
  45535. };
  45536. /**
  45537. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45538. */
  45539. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45540. this._needProjectionMatrixCompute = true;
  45541. };
  45542. /**
  45543. * Get the world matrix of the sahdow lights.
  45544. * @ignore Internal Use Only
  45545. */
  45546. ShadowLight.prototype._getWorldMatrix = function () {
  45547. if (!this._worldMatrix) {
  45548. this._worldMatrix = BABYLON.Matrix.Identity();
  45549. }
  45550. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45551. return this._worldMatrix;
  45552. };
  45553. /**
  45554. * Gets the minZ used for shadow according to both the scene and the light.
  45555. * @param activeCamera The camera we are returning the min for
  45556. * @returns the depth min z
  45557. */
  45558. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45559. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45560. };
  45561. /**
  45562. * Gets the maxZ used for shadow according to both the scene and the light.
  45563. * @param activeCamera The camera we are returning the max for
  45564. * @returns the depth max z
  45565. */
  45566. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45567. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45568. };
  45569. /**
  45570. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45571. * @param matrix The materix to updated with the projection information
  45572. * @param viewMatrix The transform matrix of the light
  45573. * @param renderList The list of mesh to render in the map
  45574. * @returns The current light
  45575. */
  45576. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45577. if (this.customProjectionMatrixBuilder) {
  45578. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45579. }
  45580. else {
  45581. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45582. }
  45583. return this;
  45584. };
  45585. __decorate([
  45586. BABYLON.serializeAsVector3()
  45587. ], ShadowLight.prototype, "position", null);
  45588. __decorate([
  45589. BABYLON.serializeAsVector3()
  45590. ], ShadowLight.prototype, "direction", null);
  45591. __decorate([
  45592. BABYLON.serialize()
  45593. ], ShadowLight.prototype, "shadowMinZ", null);
  45594. __decorate([
  45595. BABYLON.serialize()
  45596. ], ShadowLight.prototype, "shadowMaxZ", null);
  45597. return ShadowLight;
  45598. }(BABYLON.Light));
  45599. BABYLON.ShadowLight = ShadowLight;
  45600. })(BABYLON || (BABYLON = {}));
  45601. //# sourceMappingURL=babylon.shadowLight.js.map
  45602. var BABYLON;
  45603. (function (BABYLON) {
  45604. /**
  45605. * A point light is a light defined by an unique point in world space.
  45606. * The light is emitted in every direction from this point.
  45607. * A good example of a point light is a standard light bulb.
  45608. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45609. */
  45610. var PointLight = /** @class */ (function (_super) {
  45611. __extends(PointLight, _super);
  45612. /**
  45613. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45614. * A PointLight emits the light in every direction.
  45615. * It can cast shadows.
  45616. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45617. * ```javascript
  45618. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45619. * ```
  45620. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45621. * @param name The light friendly name
  45622. * @param position The position of the point light in the scene
  45623. * @param scene The scene the lights belongs to
  45624. */
  45625. function PointLight(name, position, scene) {
  45626. var _this = _super.call(this, name, scene) || this;
  45627. _this._shadowAngle = Math.PI / 2;
  45628. _this.position = position;
  45629. return _this;
  45630. }
  45631. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45632. /**
  45633. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45634. * This specifies what angle the shadow will use to be created.
  45635. *
  45636. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45637. */
  45638. get: function () {
  45639. return this._shadowAngle;
  45640. },
  45641. /**
  45642. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45643. * This specifies what angle the shadow will use to be created.
  45644. *
  45645. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45646. */
  45647. set: function (value) {
  45648. this._shadowAngle = value;
  45649. this.forceProjectionMatrixCompute();
  45650. },
  45651. enumerable: true,
  45652. configurable: true
  45653. });
  45654. Object.defineProperty(PointLight.prototype, "direction", {
  45655. /**
  45656. * Gets the direction if it has been set.
  45657. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45658. */
  45659. get: function () {
  45660. return this._direction;
  45661. },
  45662. /**
  45663. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45664. */
  45665. set: function (value) {
  45666. var previousNeedCube = this.needCube();
  45667. this._direction = value;
  45668. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45669. this._shadowGenerator.recreateShadowMap();
  45670. }
  45671. },
  45672. enumerable: true,
  45673. configurable: true
  45674. });
  45675. /**
  45676. * Returns the string "PointLight"
  45677. * @returns the class name
  45678. */
  45679. PointLight.prototype.getClassName = function () {
  45680. return "PointLight";
  45681. };
  45682. /**
  45683. * Returns the integer 0.
  45684. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45685. */
  45686. PointLight.prototype.getTypeID = function () {
  45687. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45688. };
  45689. /**
  45690. * Specifies wether or not the shadowmap should be a cube texture.
  45691. * @returns true if the shadowmap needs to be a cube texture.
  45692. */
  45693. PointLight.prototype.needCube = function () {
  45694. return !this.direction;
  45695. };
  45696. /**
  45697. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45698. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45699. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45700. */
  45701. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45702. if (this.direction) {
  45703. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45704. }
  45705. else {
  45706. switch (faceIndex) {
  45707. case 0:
  45708. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45709. case 1:
  45710. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45711. case 2:
  45712. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45713. case 3:
  45714. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45715. case 4:
  45716. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45717. case 5:
  45718. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45719. }
  45720. }
  45721. return BABYLON.Vector3.Zero();
  45722. };
  45723. /**
  45724. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45725. * - fov = PI / 2
  45726. * - aspect ratio : 1.0
  45727. * - z-near and far equal to the active camera minZ and maxZ.
  45728. * Returns the PointLight.
  45729. */
  45730. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45731. var activeCamera = this.getScene().activeCamera;
  45732. if (!activeCamera) {
  45733. return;
  45734. }
  45735. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45736. };
  45737. PointLight.prototype._buildUniformLayout = function () {
  45738. this._uniformBuffer.addUniform("vLightData", 4);
  45739. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45740. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45741. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45742. this._uniformBuffer.addUniform("depthValues", 2);
  45743. this._uniformBuffer.create();
  45744. };
  45745. /**
  45746. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45747. * @param effect The effect to update
  45748. * @param lightIndex The index of the light in the effect to update
  45749. * @returns The point light
  45750. */
  45751. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45752. if (this.computeTransformedInformation()) {
  45753. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45754. return this;
  45755. }
  45756. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45757. return this;
  45758. };
  45759. __decorate([
  45760. BABYLON.serialize()
  45761. ], PointLight.prototype, "shadowAngle", null);
  45762. return PointLight;
  45763. }(BABYLON.ShadowLight));
  45764. BABYLON.PointLight = PointLight;
  45765. })(BABYLON || (BABYLON = {}));
  45766. //# sourceMappingURL=babylon.pointLight.js.map
  45767. var BABYLON;
  45768. (function (BABYLON) {
  45769. /**
  45770. * A directional light is defined by a direction (what a surprise!).
  45771. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45772. * 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.
  45773. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45774. */
  45775. var DirectionalLight = /** @class */ (function (_super) {
  45776. __extends(DirectionalLight, _super);
  45777. /**
  45778. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45779. * The directional light is emitted from everywhere in the given direction.
  45780. * It can cast shawdows.
  45781. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45782. * @param name The friendly name of the light
  45783. * @param direction The direction of the light
  45784. * @param scene The scene the light belongs to
  45785. */
  45786. function DirectionalLight(name, direction, scene) {
  45787. var _this = _super.call(this, name, scene) || this;
  45788. _this._shadowFrustumSize = 0;
  45789. _this._shadowOrthoScale = 0.5;
  45790. /**
  45791. * Automatically compute the projection matrix to best fit (including all the casters)
  45792. * on each frame.
  45793. */
  45794. _this.autoUpdateExtends = true;
  45795. // Cache
  45796. _this._orthoLeft = Number.MAX_VALUE;
  45797. _this._orthoRight = Number.MIN_VALUE;
  45798. _this._orthoTop = Number.MIN_VALUE;
  45799. _this._orthoBottom = Number.MAX_VALUE;
  45800. _this.position = direction.scale(-1.0);
  45801. _this.direction = direction;
  45802. return _this;
  45803. }
  45804. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45805. /**
  45806. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45807. */
  45808. get: function () {
  45809. return this._shadowFrustumSize;
  45810. },
  45811. /**
  45812. * Specifies a fix frustum size for the shadow generation.
  45813. */
  45814. set: function (value) {
  45815. this._shadowFrustumSize = value;
  45816. this.forceProjectionMatrixCompute();
  45817. },
  45818. enumerable: true,
  45819. configurable: true
  45820. });
  45821. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45822. /**
  45823. * Gets the shadow projection scale against the optimal computed one.
  45824. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45825. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45826. */
  45827. get: function () {
  45828. return this._shadowOrthoScale;
  45829. },
  45830. /**
  45831. * Sets the shadow projection scale against the optimal computed one.
  45832. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45833. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45834. */
  45835. set: function (value) {
  45836. this._shadowOrthoScale = value;
  45837. this.forceProjectionMatrixCompute();
  45838. },
  45839. enumerable: true,
  45840. configurable: true
  45841. });
  45842. /**
  45843. * Returns the string "DirectionalLight".
  45844. * @return The class name
  45845. */
  45846. DirectionalLight.prototype.getClassName = function () {
  45847. return "DirectionalLight";
  45848. };
  45849. /**
  45850. * Returns the integer 1.
  45851. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45852. */
  45853. DirectionalLight.prototype.getTypeID = function () {
  45854. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45855. };
  45856. /**
  45857. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45858. * Returns the DirectionalLight Shadow projection matrix.
  45859. */
  45860. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45861. if (this.shadowFrustumSize > 0) {
  45862. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45863. }
  45864. else {
  45865. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45866. }
  45867. };
  45868. /**
  45869. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45870. * Returns the DirectionalLight Shadow projection matrix.
  45871. */
  45872. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45873. var activeCamera = this.getScene().activeCamera;
  45874. if (!activeCamera) {
  45875. return;
  45876. }
  45877. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45878. };
  45879. /**
  45880. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45881. * Returns the DirectionalLight Shadow projection matrix.
  45882. */
  45883. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45884. var activeCamera = this.getScene().activeCamera;
  45885. if (!activeCamera) {
  45886. return;
  45887. }
  45888. // Check extends
  45889. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45890. var tempVector3 = BABYLON.Vector3.Zero();
  45891. this._orthoLeft = Number.MAX_VALUE;
  45892. this._orthoRight = Number.MIN_VALUE;
  45893. this._orthoTop = Number.MIN_VALUE;
  45894. this._orthoBottom = Number.MAX_VALUE;
  45895. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45896. var mesh = renderList[meshIndex];
  45897. if (!mesh) {
  45898. continue;
  45899. }
  45900. var boundingInfo = mesh.getBoundingInfo();
  45901. var boundingBox = boundingInfo.boundingBox;
  45902. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45903. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45904. if (tempVector3.x < this._orthoLeft)
  45905. this._orthoLeft = tempVector3.x;
  45906. if (tempVector3.y < this._orthoBottom)
  45907. this._orthoBottom = tempVector3.y;
  45908. if (tempVector3.x > this._orthoRight)
  45909. this._orthoRight = tempVector3.x;
  45910. if (tempVector3.y > this._orthoTop)
  45911. this._orthoTop = tempVector3.y;
  45912. }
  45913. }
  45914. }
  45915. var xOffset = this._orthoRight - this._orthoLeft;
  45916. var yOffset = this._orthoTop - this._orthoBottom;
  45917. 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);
  45918. };
  45919. DirectionalLight.prototype._buildUniformLayout = function () {
  45920. this._uniformBuffer.addUniform("vLightData", 4);
  45921. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45922. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45923. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45924. this._uniformBuffer.addUniform("depthValues", 2);
  45925. this._uniformBuffer.create();
  45926. };
  45927. /**
  45928. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45929. * @param effect The effect to update
  45930. * @param lightIndex The index of the light in the effect to update
  45931. * @returns The directional light
  45932. */
  45933. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45934. if (this.computeTransformedInformation()) {
  45935. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45936. return this;
  45937. }
  45938. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45939. return this;
  45940. };
  45941. /**
  45942. * Gets the minZ used for shadow according to both the scene and the light.
  45943. *
  45944. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45945. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45946. * @param activeCamera The camera we are returning the min for
  45947. * @returns the depth min z
  45948. */
  45949. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45950. return 1;
  45951. };
  45952. /**
  45953. * Gets the maxZ used for shadow according to both the scene and the light.
  45954. *
  45955. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45956. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45957. * @param activeCamera The camera we are returning the max for
  45958. * @returns the depth max z
  45959. */
  45960. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45961. return 1;
  45962. };
  45963. __decorate([
  45964. BABYLON.serialize()
  45965. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45966. __decorate([
  45967. BABYLON.serialize()
  45968. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45969. __decorate([
  45970. BABYLON.serialize()
  45971. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45972. return DirectionalLight;
  45973. }(BABYLON.ShadowLight));
  45974. BABYLON.DirectionalLight = DirectionalLight;
  45975. })(BABYLON || (BABYLON = {}));
  45976. //# sourceMappingURL=babylon.directionalLight.js.map
  45977. var BABYLON;
  45978. (function (BABYLON) {
  45979. /**
  45980. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45981. * These values define a cone of light starting from the position, emitting toward the direction.
  45982. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45983. * and the exponent defines the speed of the decay of the light with distance (reach).
  45984. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45985. */
  45986. var SpotLight = /** @class */ (function (_super) {
  45987. __extends(SpotLight, _super);
  45988. /**
  45989. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45990. * It can cast shadows.
  45991. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45992. * @param name The light friendly name
  45993. * @param position The position of the spot light in the scene
  45994. * @param direction The direction of the light in the scene
  45995. * @param angle The cone angle of the light in Radians
  45996. * @param exponent The light decay speed with the distance from the emission spot
  45997. * @param scene The scene the lights belongs to
  45998. */
  45999. function SpotLight(name, position, direction, angle, exponent, scene) {
  46000. var _this = _super.call(this, name, scene) || this;
  46001. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46002. _this._projectionTextureLightNear = 1e-6;
  46003. _this._projectionTextureLightFar = 1000.0;
  46004. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46005. _this._projectionTextureViewLightDirty = true;
  46006. _this._projectionTextureProjectionLightDirty = true;
  46007. _this._projectionTextureDirty = true;
  46008. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46009. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46010. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46011. _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);
  46012. _this.position = position;
  46013. _this.direction = direction;
  46014. _this.angle = angle;
  46015. _this.exponent = exponent;
  46016. return _this;
  46017. }
  46018. Object.defineProperty(SpotLight.prototype, "angle", {
  46019. /**
  46020. * Gets the cone angle of the spot light in Radians.
  46021. */
  46022. get: function () {
  46023. return this._angle;
  46024. },
  46025. /**
  46026. * Sets the cone angle of the spot light in Radians.
  46027. */
  46028. set: function (value) {
  46029. this._angle = value;
  46030. this._projectionTextureProjectionLightDirty = true;
  46031. this.forceProjectionMatrixCompute();
  46032. },
  46033. enumerable: true,
  46034. configurable: true
  46035. });
  46036. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46037. /**
  46038. * Allows scaling the angle of the light for shadow generation only.
  46039. */
  46040. get: function () {
  46041. return this._shadowAngleScale;
  46042. },
  46043. /**
  46044. * Allows scaling the angle of the light for shadow generation only.
  46045. */
  46046. set: function (value) {
  46047. this._shadowAngleScale = value;
  46048. this.forceProjectionMatrixCompute();
  46049. },
  46050. enumerable: true,
  46051. configurable: true
  46052. });
  46053. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46054. /**
  46055. * Allows reading the projecton texture
  46056. */
  46057. get: function () {
  46058. return this._projectionTextureMatrix;
  46059. },
  46060. enumerable: true,
  46061. configurable: true
  46062. });
  46063. ;
  46064. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46065. /**
  46066. * Gets the near clip of the Spotlight for texture projection.
  46067. */
  46068. get: function () {
  46069. return this._projectionTextureLightNear;
  46070. },
  46071. /**
  46072. * Sets the near clip of the Spotlight for texture projection.
  46073. */
  46074. set: function (value) {
  46075. this._projectionTextureLightNear = value;
  46076. this._projectionTextureProjectionLightDirty = true;
  46077. },
  46078. enumerable: true,
  46079. configurable: true
  46080. });
  46081. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46082. /**
  46083. * Gets the far clip of the Spotlight for texture projection.
  46084. */
  46085. get: function () {
  46086. return this._projectionTextureLightFar;
  46087. },
  46088. /**
  46089. * Sets the far clip of the Spotlight for texture projection.
  46090. */
  46091. set: function (value) {
  46092. this._projectionTextureLightFar = value;
  46093. this._projectionTextureProjectionLightDirty = true;
  46094. },
  46095. enumerable: true,
  46096. configurable: true
  46097. });
  46098. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46099. /**
  46100. * Gets the Up vector of the Spotlight for texture projection.
  46101. */
  46102. get: function () {
  46103. return this._projectionTextureUpDirection;
  46104. },
  46105. /**
  46106. * Sets the Up vector of the Spotlight for texture projection.
  46107. */
  46108. set: function (value) {
  46109. this._projectionTextureUpDirection = value;
  46110. this._projectionTextureProjectionLightDirty = true;
  46111. },
  46112. enumerable: true,
  46113. configurable: true
  46114. });
  46115. ;
  46116. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46117. /**
  46118. * Gets the projection texture of the light.
  46119. */
  46120. get: function () {
  46121. return this._projectionTexture;
  46122. },
  46123. /**
  46124. * Sets the projection texture of the light.
  46125. */
  46126. set: function (value) {
  46127. this._projectionTexture = value;
  46128. this._projectionTextureDirty = true;
  46129. },
  46130. enumerable: true,
  46131. configurable: true
  46132. });
  46133. /**
  46134. * Returns the string "SpotLight".
  46135. * @returns the class name
  46136. */
  46137. SpotLight.prototype.getClassName = function () {
  46138. return "SpotLight";
  46139. };
  46140. /**
  46141. * Returns the integer 2.
  46142. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46143. */
  46144. SpotLight.prototype.getTypeID = function () {
  46145. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46146. };
  46147. /**
  46148. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46149. */
  46150. SpotLight.prototype._setDirection = function (value) {
  46151. _super.prototype._setDirection.call(this, value);
  46152. this._projectionTextureViewLightDirty = true;
  46153. };
  46154. /**
  46155. * Overrides the position setter to recompute the projection texture view light Matrix.
  46156. */
  46157. SpotLight.prototype._setPosition = function (value) {
  46158. _super.prototype._setPosition.call(this, value);
  46159. this._projectionTextureViewLightDirty = true;
  46160. };
  46161. /**
  46162. * 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.
  46163. * Returns the SpotLight.
  46164. */
  46165. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46166. var activeCamera = this.getScene().activeCamera;
  46167. if (!activeCamera) {
  46168. return;
  46169. }
  46170. this._shadowAngleScale = this._shadowAngleScale || 1;
  46171. var angle = this._shadowAngleScale * this._angle;
  46172. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46173. };
  46174. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46175. this._projectionTextureViewLightDirty = false;
  46176. this._projectionTextureDirty = true;
  46177. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46178. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46179. };
  46180. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46181. this._projectionTextureProjectionLightDirty = false;
  46182. this._projectionTextureDirty = true;
  46183. var light_far = this.projectionTextureLightFar;
  46184. var light_near = this.projectionTextureLightNear;
  46185. var P = light_far / (light_far - light_near);
  46186. var Q = -P * light_near;
  46187. var S = 1.0 / Math.tan(this._angle / 2.0);
  46188. var A = 1.0;
  46189. 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);
  46190. };
  46191. /**
  46192. * Main function for light texture projection matrix computing.
  46193. */
  46194. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46195. this._projectionTextureDirty = false;
  46196. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46197. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46198. };
  46199. SpotLight.prototype._buildUniformLayout = function () {
  46200. this._uniformBuffer.addUniform("vLightData", 4);
  46201. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46202. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46203. this._uniformBuffer.addUniform("vLightDirection", 3);
  46204. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46205. this._uniformBuffer.addUniform("depthValues", 2);
  46206. this._uniformBuffer.create();
  46207. };
  46208. /**
  46209. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46210. * @param effect The effect to update
  46211. * @param lightIndex The index of the light in the effect to update
  46212. * @returns The spot light
  46213. */
  46214. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46215. var normalizeDirection;
  46216. if (this.computeTransformedInformation()) {
  46217. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46218. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46219. }
  46220. else {
  46221. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46222. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46223. }
  46224. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46225. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46226. if (this._projectionTextureViewLightDirty) {
  46227. this._computeProjectionTextureViewLightMatrix();
  46228. }
  46229. if (this._projectionTextureProjectionLightDirty) {
  46230. this._computeProjectionTextureProjectionLightMatrix();
  46231. }
  46232. if (this._projectionTextureDirty) {
  46233. this._computeProjectionTextureMatrix();
  46234. }
  46235. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46236. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46237. }
  46238. return this;
  46239. };
  46240. /**
  46241. * Disposes the light and the associated resources.
  46242. */
  46243. SpotLight.prototype.dispose = function () {
  46244. _super.prototype.dispose.call(this);
  46245. if (this._projectionTexture) {
  46246. this._projectionTexture.dispose();
  46247. }
  46248. };
  46249. __decorate([
  46250. BABYLON.serialize()
  46251. ], SpotLight.prototype, "angle", null);
  46252. __decorate([
  46253. BABYLON.serialize()
  46254. ], SpotLight.prototype, "shadowAngleScale", null);
  46255. __decorate([
  46256. BABYLON.serialize()
  46257. ], SpotLight.prototype, "exponent", void 0);
  46258. __decorate([
  46259. BABYLON.serialize()
  46260. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46261. __decorate([
  46262. BABYLON.serialize()
  46263. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46264. __decorate([
  46265. BABYLON.serialize()
  46266. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46267. __decorate([
  46268. BABYLON.serializeAsTexture("projectedLightTexture")
  46269. ], SpotLight.prototype, "_projectionTexture", void 0);
  46270. return SpotLight;
  46271. }(BABYLON.ShadowLight));
  46272. BABYLON.SpotLight = SpotLight;
  46273. })(BABYLON || (BABYLON = {}));
  46274. //# sourceMappingURL=babylon.spotLight.js.map
  46275. var BABYLON;
  46276. (function (BABYLON) {
  46277. /**
  46278. * Class used to override all child animations of a given target
  46279. */
  46280. var AnimationPropertiesOverride = /** @class */ (function () {
  46281. function AnimationPropertiesOverride() {
  46282. /**
  46283. * Gets or sets a value indicating if animation blending must be used
  46284. */
  46285. this.enableBlending = false;
  46286. /**
  46287. * Gets or sets the blending speed to use when enableBlending is true
  46288. */
  46289. this.blendingSpeed = 0.01;
  46290. /**
  46291. * Gets or sets the default loop mode to use
  46292. */
  46293. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46294. }
  46295. return AnimationPropertiesOverride;
  46296. }());
  46297. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46298. })(BABYLON || (BABYLON = {}));
  46299. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46300. var BABYLON;
  46301. (function (BABYLON) {
  46302. var AnimationRange = /** @class */ (function () {
  46303. function AnimationRange(name, from, to) {
  46304. this.name = name;
  46305. this.from = from;
  46306. this.to = to;
  46307. }
  46308. AnimationRange.prototype.clone = function () {
  46309. return new AnimationRange(this.name, this.from, this.to);
  46310. };
  46311. return AnimationRange;
  46312. }());
  46313. BABYLON.AnimationRange = AnimationRange;
  46314. /**
  46315. * Composed of a frame, and an action function
  46316. */
  46317. var AnimationEvent = /** @class */ (function () {
  46318. function AnimationEvent(frame, action, onlyOnce) {
  46319. this.frame = frame;
  46320. this.action = action;
  46321. this.onlyOnce = onlyOnce;
  46322. this.isDone = false;
  46323. }
  46324. return AnimationEvent;
  46325. }());
  46326. BABYLON.AnimationEvent = AnimationEvent;
  46327. var PathCursor = /** @class */ (function () {
  46328. function PathCursor(path) {
  46329. this.path = path;
  46330. this._onchange = new Array();
  46331. this.value = 0;
  46332. this.animations = new Array();
  46333. }
  46334. PathCursor.prototype.getPoint = function () {
  46335. var point = this.path.getPointAtLengthPosition(this.value);
  46336. return new BABYLON.Vector3(point.x, 0, point.y);
  46337. };
  46338. PathCursor.prototype.moveAhead = function (step) {
  46339. if (step === void 0) { step = 0.002; }
  46340. this.move(step);
  46341. return this;
  46342. };
  46343. PathCursor.prototype.moveBack = function (step) {
  46344. if (step === void 0) { step = 0.002; }
  46345. this.move(-step);
  46346. return this;
  46347. };
  46348. PathCursor.prototype.move = function (step) {
  46349. if (Math.abs(step) > 1) {
  46350. throw "step size should be less than 1.";
  46351. }
  46352. this.value += step;
  46353. this.ensureLimits();
  46354. this.raiseOnChange();
  46355. return this;
  46356. };
  46357. PathCursor.prototype.ensureLimits = function () {
  46358. while (this.value > 1) {
  46359. this.value -= 1;
  46360. }
  46361. while (this.value < 0) {
  46362. this.value += 1;
  46363. }
  46364. return this;
  46365. };
  46366. // used by animation engine
  46367. PathCursor.prototype.raiseOnChange = function () {
  46368. var _this = this;
  46369. this._onchange.forEach(function (f) { return f(_this); });
  46370. return this;
  46371. };
  46372. PathCursor.prototype.onchange = function (f) {
  46373. this._onchange.push(f);
  46374. return this;
  46375. };
  46376. return PathCursor;
  46377. }());
  46378. BABYLON.PathCursor = PathCursor;
  46379. var AnimationKeyInterpolation;
  46380. (function (AnimationKeyInterpolation) {
  46381. /**
  46382. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46383. */
  46384. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46385. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46386. var Animation = /** @class */ (function () {
  46387. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46388. this.name = name;
  46389. this.targetProperty = targetProperty;
  46390. this.framePerSecond = framePerSecond;
  46391. this.dataType = dataType;
  46392. this.loopMode = loopMode;
  46393. this.enableBlending = enableBlending;
  46394. this._runtimeAnimations = new Array();
  46395. // The set of event that will be linked to this animation
  46396. this._events = new Array();
  46397. this.blendingSpeed = 0.01;
  46398. this._ranges = {};
  46399. this.targetPropertyPath = targetProperty.split(".");
  46400. this.dataType = dataType;
  46401. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46402. }
  46403. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46404. var dataType = undefined;
  46405. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46406. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46407. }
  46408. else if (from instanceof BABYLON.Quaternion) {
  46409. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46410. }
  46411. else if (from instanceof BABYLON.Vector3) {
  46412. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46413. }
  46414. else if (from instanceof BABYLON.Vector2) {
  46415. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46416. }
  46417. else if (from instanceof BABYLON.Color3) {
  46418. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46419. }
  46420. else if (from instanceof BABYLON.Size) {
  46421. dataType = Animation.ANIMATIONTYPE_SIZE;
  46422. }
  46423. if (dataType == undefined) {
  46424. return null;
  46425. }
  46426. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46427. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46428. animation.setKeys(keys);
  46429. if (easingFunction !== undefined) {
  46430. animation.setEasingFunction(easingFunction);
  46431. }
  46432. return animation;
  46433. };
  46434. /**
  46435. * Sets up an animation.
  46436. * @param property the property to animate
  46437. * @param animationType the animation type to apply
  46438. * @param easingFunction the easing function used in the animation
  46439. * @returns The created animation
  46440. */
  46441. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46442. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46443. animation.setEasingFunction(easingFunction);
  46444. return animation;
  46445. };
  46446. /**
  46447. * Create and start an animation on a node
  46448. * @param {string} name defines the name of the global animation that will be run on all nodes
  46449. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46450. * @param {string} targetProperty defines property to animate
  46451. * @param {number} framePerSecond defines the number of frame per second yo use
  46452. * @param {number} totalFrame defines the number of frames in total
  46453. * @param {any} from defines the initial value
  46454. * @param {any} to defines the final value
  46455. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46456. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46457. * @param onAnimationEnd defines the callback to call when animation end
  46458. * @returns the animatable created for this animation
  46459. */
  46460. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46461. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46462. if (!animation) {
  46463. return null;
  46464. }
  46465. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46466. };
  46467. /**
  46468. * Create and start an animation on a node and its descendants
  46469. * @param {string} name defines the name of the global animation that will be run on all nodes
  46470. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46471. * @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.
  46472. * @param {string} targetProperty defines property to animate
  46473. * @param {number} framePerSecond defines the number of frame per second yo use
  46474. * @param {number} totalFrame defines the number of frames in total
  46475. * @param {any} from defines the initial value
  46476. * @param {any} to defines the final value
  46477. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46478. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46479. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46480. * @returns the list of animatables created for all nodes
  46481. * @example https://www.babylonjs-playground.com/#MH0VLI
  46482. */
  46483. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46484. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46485. if (!animation) {
  46486. return null;
  46487. }
  46488. var scene = node.getScene();
  46489. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46490. };
  46491. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46492. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46493. if (!animation) {
  46494. return null;
  46495. }
  46496. node.animations.push(animation);
  46497. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46498. };
  46499. /**
  46500. * Transition property of the Camera to the target Value.
  46501. * @param property The property to transition
  46502. * @param targetValue The target Value of the property
  46503. * @param host The object where the property to animate belongs
  46504. * @param scene Scene used to run the animation
  46505. * @param frameRate Framerate (in frame/s) to use
  46506. * @param transition The transition type we want to use
  46507. * @param duration The duration of the animation, in milliseconds
  46508. * @param onAnimationEnd Call back trigger at the end of the animation.
  46509. */
  46510. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46511. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46512. if (duration <= 0) {
  46513. host[property] = targetValue;
  46514. if (onAnimationEnd) {
  46515. onAnimationEnd();
  46516. }
  46517. return null;
  46518. }
  46519. var endFrame = frameRate * (duration / 1000);
  46520. transition.setKeys([{
  46521. frame: 0,
  46522. value: host[property].clone ? host[property].clone() : host[property]
  46523. },
  46524. {
  46525. frame: endFrame,
  46526. value: targetValue
  46527. }]);
  46528. if (!host.animations) {
  46529. host.animations = [];
  46530. }
  46531. host.animations.push(transition);
  46532. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46533. animation.onAnimationEnd = onAnimationEnd;
  46534. return animation;
  46535. };
  46536. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46537. /**
  46538. * Return the array of runtime animations currently using this animation
  46539. */
  46540. get: function () {
  46541. return this._runtimeAnimations;
  46542. },
  46543. enumerable: true,
  46544. configurable: true
  46545. });
  46546. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46547. get: function () {
  46548. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46549. var runtimeAnimation = _a[_i];
  46550. if (!runtimeAnimation.isStopped) {
  46551. return true;
  46552. }
  46553. }
  46554. return false;
  46555. },
  46556. enumerable: true,
  46557. configurable: true
  46558. });
  46559. // Methods
  46560. /**
  46561. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46562. */
  46563. Animation.prototype.toString = function (fullDetails) {
  46564. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46565. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46566. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46567. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46568. if (fullDetails) {
  46569. ret += ", Ranges: {";
  46570. var first = true;
  46571. for (var name in this._ranges) {
  46572. if (first) {
  46573. ret += ", ";
  46574. first = false;
  46575. }
  46576. ret += name;
  46577. }
  46578. ret += "}";
  46579. }
  46580. return ret;
  46581. };
  46582. /**
  46583. * Add an event to this animation.
  46584. */
  46585. Animation.prototype.addEvent = function (event) {
  46586. this._events.push(event);
  46587. };
  46588. /**
  46589. * Remove all events found at the given frame
  46590. * @param frame
  46591. */
  46592. Animation.prototype.removeEvents = function (frame) {
  46593. for (var index = 0; index < this._events.length; index++) {
  46594. if (this._events[index].frame === frame) {
  46595. this._events.splice(index, 1);
  46596. index--;
  46597. }
  46598. }
  46599. };
  46600. Animation.prototype.getEvents = function () {
  46601. return this._events;
  46602. };
  46603. Animation.prototype.createRange = function (name, from, to) {
  46604. // check name not already in use; could happen for bones after serialized
  46605. if (!this._ranges[name]) {
  46606. this._ranges[name] = new AnimationRange(name, from, to);
  46607. }
  46608. };
  46609. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46610. if (deleteFrames === void 0) { deleteFrames = true; }
  46611. var range = this._ranges[name];
  46612. if (!range) {
  46613. return;
  46614. }
  46615. if (deleteFrames) {
  46616. var from = range.from;
  46617. var to = range.to;
  46618. // this loop MUST go high to low for multiple splices to work
  46619. for (var key = this._keys.length - 1; key >= 0; key--) {
  46620. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46621. this._keys.splice(key, 1);
  46622. }
  46623. }
  46624. }
  46625. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46626. };
  46627. Animation.prototype.getRange = function (name) {
  46628. return this._ranges[name];
  46629. };
  46630. Animation.prototype.getKeys = function () {
  46631. return this._keys;
  46632. };
  46633. Animation.prototype.getHighestFrame = function () {
  46634. var ret = 0;
  46635. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46636. if (ret < this._keys[key].frame) {
  46637. ret = this._keys[key].frame;
  46638. }
  46639. }
  46640. return ret;
  46641. };
  46642. Animation.prototype.getEasingFunction = function () {
  46643. return this._easingFunction;
  46644. };
  46645. Animation.prototype.setEasingFunction = function (easingFunction) {
  46646. this._easingFunction = easingFunction;
  46647. };
  46648. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46649. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46650. };
  46651. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46652. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46653. };
  46654. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46655. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46656. };
  46657. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46658. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46659. };
  46660. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46661. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46662. };
  46663. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46664. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46665. };
  46666. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46667. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46668. };
  46669. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46670. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46671. };
  46672. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46673. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46674. };
  46675. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46676. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46677. };
  46678. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46679. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46680. };
  46681. Animation.prototype.clone = function () {
  46682. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46683. clone.enableBlending = this.enableBlending;
  46684. clone.blendingSpeed = this.blendingSpeed;
  46685. if (this._keys) {
  46686. clone.setKeys(this._keys);
  46687. }
  46688. if (this._ranges) {
  46689. clone._ranges = {};
  46690. for (var name in this._ranges) {
  46691. var range = this._ranges[name];
  46692. if (!range) {
  46693. continue;
  46694. }
  46695. clone._ranges[name] = range.clone();
  46696. }
  46697. }
  46698. return clone;
  46699. };
  46700. Animation.prototype.setKeys = function (values) {
  46701. this._keys = values.slice(0);
  46702. };
  46703. Animation.prototype.serialize = function () {
  46704. var serializationObject = {};
  46705. serializationObject.name = this.name;
  46706. serializationObject.property = this.targetProperty;
  46707. serializationObject.framePerSecond = this.framePerSecond;
  46708. serializationObject.dataType = this.dataType;
  46709. serializationObject.loopBehavior = this.loopMode;
  46710. serializationObject.enableBlending = this.enableBlending;
  46711. serializationObject.blendingSpeed = this.blendingSpeed;
  46712. var dataType = this.dataType;
  46713. serializationObject.keys = [];
  46714. var keys = this.getKeys();
  46715. for (var index = 0; index < keys.length; index++) {
  46716. var animationKey = keys[index];
  46717. var key = {};
  46718. key.frame = animationKey.frame;
  46719. switch (dataType) {
  46720. case Animation.ANIMATIONTYPE_FLOAT:
  46721. key.values = [animationKey.value];
  46722. break;
  46723. case Animation.ANIMATIONTYPE_QUATERNION:
  46724. case Animation.ANIMATIONTYPE_MATRIX:
  46725. case Animation.ANIMATIONTYPE_VECTOR3:
  46726. case Animation.ANIMATIONTYPE_COLOR3:
  46727. key.values = animationKey.value.asArray();
  46728. break;
  46729. }
  46730. serializationObject.keys.push(key);
  46731. }
  46732. serializationObject.ranges = [];
  46733. for (var name in this._ranges) {
  46734. var source = this._ranges[name];
  46735. if (!source) {
  46736. continue;
  46737. }
  46738. var range = {};
  46739. range.name = name;
  46740. range.from = source.from;
  46741. range.to = source.to;
  46742. serializationObject.ranges.push(range);
  46743. }
  46744. return serializationObject;
  46745. };
  46746. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46747. get: function () {
  46748. return Animation._ANIMATIONTYPE_FLOAT;
  46749. },
  46750. enumerable: true,
  46751. configurable: true
  46752. });
  46753. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46754. get: function () {
  46755. return Animation._ANIMATIONTYPE_VECTOR3;
  46756. },
  46757. enumerable: true,
  46758. configurable: true
  46759. });
  46760. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46761. get: function () {
  46762. return Animation._ANIMATIONTYPE_VECTOR2;
  46763. },
  46764. enumerable: true,
  46765. configurable: true
  46766. });
  46767. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46768. get: function () {
  46769. return Animation._ANIMATIONTYPE_SIZE;
  46770. },
  46771. enumerable: true,
  46772. configurable: true
  46773. });
  46774. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46775. get: function () {
  46776. return Animation._ANIMATIONTYPE_QUATERNION;
  46777. },
  46778. enumerable: true,
  46779. configurable: true
  46780. });
  46781. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46782. get: function () {
  46783. return Animation._ANIMATIONTYPE_MATRIX;
  46784. },
  46785. enumerable: true,
  46786. configurable: true
  46787. });
  46788. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46789. get: function () {
  46790. return Animation._ANIMATIONTYPE_COLOR3;
  46791. },
  46792. enumerable: true,
  46793. configurable: true
  46794. });
  46795. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46796. get: function () {
  46797. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46798. },
  46799. enumerable: true,
  46800. configurable: true
  46801. });
  46802. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46803. get: function () {
  46804. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46805. },
  46806. enumerable: true,
  46807. configurable: true
  46808. });
  46809. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46810. get: function () {
  46811. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46812. },
  46813. enumerable: true,
  46814. configurable: true
  46815. });
  46816. Animation.Parse = function (parsedAnimation) {
  46817. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46818. var dataType = parsedAnimation.dataType;
  46819. var keys = [];
  46820. var data;
  46821. var index;
  46822. if (parsedAnimation.enableBlending) {
  46823. animation.enableBlending = parsedAnimation.enableBlending;
  46824. }
  46825. if (parsedAnimation.blendingSpeed) {
  46826. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46827. }
  46828. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46829. var key = parsedAnimation.keys[index];
  46830. var inTangent;
  46831. var outTangent;
  46832. switch (dataType) {
  46833. case Animation.ANIMATIONTYPE_FLOAT:
  46834. data = key.values[0];
  46835. if (key.values.length >= 1) {
  46836. inTangent = key.values[1];
  46837. }
  46838. if (key.values.length >= 2) {
  46839. outTangent = key.values[2];
  46840. }
  46841. break;
  46842. case Animation.ANIMATIONTYPE_QUATERNION:
  46843. data = BABYLON.Quaternion.FromArray(key.values);
  46844. if (key.values.length >= 8) {
  46845. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46846. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46847. inTangent = _inTangent;
  46848. }
  46849. }
  46850. if (key.values.length >= 12) {
  46851. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46852. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46853. outTangent = _outTangent;
  46854. }
  46855. }
  46856. break;
  46857. case Animation.ANIMATIONTYPE_MATRIX:
  46858. data = BABYLON.Matrix.FromArray(key.values);
  46859. break;
  46860. case Animation.ANIMATIONTYPE_COLOR3:
  46861. data = BABYLON.Color3.FromArray(key.values);
  46862. break;
  46863. case Animation.ANIMATIONTYPE_VECTOR3:
  46864. default:
  46865. data = BABYLON.Vector3.FromArray(key.values);
  46866. break;
  46867. }
  46868. var keyData = {};
  46869. keyData.frame = key.frame;
  46870. keyData.value = data;
  46871. if (inTangent != undefined) {
  46872. keyData.inTangent = inTangent;
  46873. }
  46874. if (outTangent != undefined) {
  46875. keyData.outTangent = outTangent;
  46876. }
  46877. keys.push(keyData);
  46878. }
  46879. animation.setKeys(keys);
  46880. if (parsedAnimation.ranges) {
  46881. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46882. data = parsedAnimation.ranges[index];
  46883. animation.createRange(data.name, data.from, data.to);
  46884. }
  46885. }
  46886. return animation;
  46887. };
  46888. Animation.AppendSerializedAnimations = function (source, destination) {
  46889. if (source.animations) {
  46890. destination.animations = [];
  46891. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46892. var animation = source.animations[animationIndex];
  46893. destination.animations.push(animation.serialize());
  46894. }
  46895. }
  46896. };
  46897. Animation.AllowMatricesInterpolation = false;
  46898. // Statics
  46899. Animation._ANIMATIONTYPE_FLOAT = 0;
  46900. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46901. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46902. Animation._ANIMATIONTYPE_MATRIX = 3;
  46903. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46904. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46905. Animation._ANIMATIONTYPE_SIZE = 6;
  46906. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46907. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46908. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46909. return Animation;
  46910. }());
  46911. BABYLON.Animation = Animation;
  46912. })(BABYLON || (BABYLON = {}));
  46913. //# sourceMappingURL=babylon.animation.js.map
  46914. var BABYLON;
  46915. (function (BABYLON) {
  46916. /**
  46917. * This class defines the direct association between an animation and a target
  46918. */
  46919. var TargetedAnimation = /** @class */ (function () {
  46920. function TargetedAnimation() {
  46921. }
  46922. return TargetedAnimation;
  46923. }());
  46924. BABYLON.TargetedAnimation = TargetedAnimation;
  46925. /**
  46926. * Use this class to create coordinated animations on multiple targets
  46927. */
  46928. var AnimationGroup = /** @class */ (function () {
  46929. function AnimationGroup(name, scene) {
  46930. if (scene === void 0) { scene = null; }
  46931. this.name = name;
  46932. this._targetedAnimations = new Array();
  46933. this._animatables = new Array();
  46934. this._from = Number.MAX_VALUE;
  46935. this._to = -Number.MAX_VALUE;
  46936. this._speedRatio = 1;
  46937. this.onAnimationEndObservable = new BABYLON.Observable();
  46938. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46939. this._scene.animationGroups.push(this);
  46940. }
  46941. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46942. /**
  46943. * Define if the animations are started
  46944. */
  46945. get: function () {
  46946. return this._isStarted;
  46947. },
  46948. enumerable: true,
  46949. configurable: true
  46950. });
  46951. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46952. /**
  46953. * Gets or sets the speed ratio to use for all animations
  46954. */
  46955. get: function () {
  46956. return this._speedRatio;
  46957. },
  46958. /**
  46959. * Gets or sets the speed ratio to use for all animations
  46960. */
  46961. set: function (value) {
  46962. if (this._speedRatio === value) {
  46963. return;
  46964. }
  46965. this._speedRatio = value;
  46966. for (var index = 0; index < this._animatables.length; index++) {
  46967. var animatable = this._animatables[index];
  46968. animatable.speedRatio = this._speedRatio;
  46969. }
  46970. },
  46971. enumerable: true,
  46972. configurable: true
  46973. });
  46974. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46975. /**
  46976. * Gets the targeted animations for this animation group
  46977. */
  46978. get: function () {
  46979. return this._targetedAnimations;
  46980. },
  46981. enumerable: true,
  46982. configurable: true
  46983. });
  46984. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  46985. /**
  46986. * returning the list of animatables controlled by this animation group.
  46987. */
  46988. get: function () {
  46989. return this._animatables;
  46990. },
  46991. enumerable: true,
  46992. configurable: true
  46993. });
  46994. /**
  46995. * Add an animation (with its target) in the group
  46996. * @param animation defines the animation we want to add
  46997. * @param target defines the target of the animation
  46998. * @returns the {BABYLON.TargetedAnimation} object
  46999. */
  47000. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47001. var targetedAnimation = {
  47002. animation: animation,
  47003. target: target
  47004. };
  47005. var keys = animation.getKeys();
  47006. if (this._from > keys[0].frame) {
  47007. this._from = keys[0].frame;
  47008. }
  47009. if (this._to < keys[keys.length - 1].frame) {
  47010. this._to = keys[keys.length - 1].frame;
  47011. }
  47012. this._targetedAnimations.push(targetedAnimation);
  47013. return targetedAnimation;
  47014. };
  47015. /**
  47016. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47017. * It can add constant keys at begin or end
  47018. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47019. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47020. */
  47021. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47022. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47023. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47024. beginFrame = Math.max(beginFrame, this._from);
  47025. endFrame = Math.min(endFrame, this._to);
  47026. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47027. var targetedAnimation = this._targetedAnimations[index];
  47028. var keys = targetedAnimation.animation.getKeys();
  47029. var startKey = keys[0];
  47030. var endKey = keys[keys.length - 1];
  47031. if (startKey.frame > beginFrame) {
  47032. var newKey = {
  47033. frame: beginFrame,
  47034. value: startKey.value,
  47035. inTangent: startKey.inTangent,
  47036. outTangent: startKey.outTangent,
  47037. interpolation: startKey.interpolation
  47038. };
  47039. keys.splice(0, 0, newKey);
  47040. }
  47041. if (endKey.frame < endFrame) {
  47042. var newKey = {
  47043. frame: endFrame,
  47044. value: endKey.value,
  47045. inTangent: endKey.outTangent,
  47046. outTangent: endKey.outTangent,
  47047. interpolation: endKey.interpolation
  47048. };
  47049. keys.push(newKey);
  47050. }
  47051. }
  47052. return this;
  47053. };
  47054. /**
  47055. * Start all animations on given targets
  47056. * @param loop defines if animations must loop
  47057. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47058. */
  47059. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47060. var _this = this;
  47061. if (loop === void 0) { loop = false; }
  47062. if (speedRatio === void 0) { speedRatio = 1; }
  47063. if (this._isStarted || this._targetedAnimations.length === 0) {
  47064. return this;
  47065. }
  47066. var _loop_1 = function () {
  47067. var targetedAnimation = this_1._targetedAnimations[index];
  47068. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47069. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47070. }));
  47071. };
  47072. var this_1 = this;
  47073. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47074. _loop_1();
  47075. }
  47076. this._speedRatio = speedRatio;
  47077. this._isStarted = true;
  47078. return this;
  47079. };
  47080. /**
  47081. * Pause all animations
  47082. */
  47083. AnimationGroup.prototype.pause = function () {
  47084. if (!this._isStarted) {
  47085. return this;
  47086. }
  47087. for (var index = 0; index < this._animatables.length; index++) {
  47088. var animatable = this._animatables[index];
  47089. animatable.pause();
  47090. }
  47091. return this;
  47092. };
  47093. /**
  47094. * Play all animations to initial state
  47095. * This function will start() the animations if they were not started or will restart() them if they were paused
  47096. * @param loop defines if animations must loop
  47097. */
  47098. AnimationGroup.prototype.play = function (loop) {
  47099. if (this.isStarted) {
  47100. if (loop !== undefined) {
  47101. for (var index = 0; index < this._animatables.length; index++) {
  47102. var animatable = this._animatables[index];
  47103. animatable.loopAnimation = loop;
  47104. }
  47105. }
  47106. this.restart();
  47107. }
  47108. else {
  47109. this.start(loop, this._speedRatio);
  47110. }
  47111. return this;
  47112. };
  47113. /**
  47114. * Reset all animations to initial state
  47115. */
  47116. AnimationGroup.prototype.reset = function () {
  47117. if (!this._isStarted) {
  47118. return this;
  47119. }
  47120. for (var index = 0; index < this._animatables.length; index++) {
  47121. var animatable = this._animatables[index];
  47122. animatable.reset();
  47123. }
  47124. return this;
  47125. };
  47126. /**
  47127. * Restart animations from key 0
  47128. */
  47129. AnimationGroup.prototype.restart = function () {
  47130. if (!this._isStarted) {
  47131. return this;
  47132. }
  47133. for (var index = 0; index < this._animatables.length; index++) {
  47134. var animatable = this._animatables[index];
  47135. animatable.restart();
  47136. }
  47137. return this;
  47138. };
  47139. /**
  47140. * Stop all animations
  47141. */
  47142. AnimationGroup.prototype.stop = function () {
  47143. if (!this._isStarted) {
  47144. return this;
  47145. }
  47146. for (var index = 0; index < this._animatables.length; index++) {
  47147. var animatable = this._animatables[index];
  47148. animatable.stop();
  47149. }
  47150. this._isStarted = false;
  47151. return this;
  47152. };
  47153. /**
  47154. * Goes to a specific frame in this animation group
  47155. *
  47156. * @param frame the frame number to go to
  47157. * @return the animationGroup
  47158. */
  47159. AnimationGroup.prototype.goToFrame = function (frame) {
  47160. if (!this._isStarted) {
  47161. return this;
  47162. }
  47163. for (var index = 0; index < this._animatables.length; index++) {
  47164. var animatable = this._animatables[index];
  47165. animatable.goToFrame(frame);
  47166. }
  47167. return this;
  47168. };
  47169. /**
  47170. * Dispose all associated resources
  47171. */
  47172. AnimationGroup.prototype.dispose = function () {
  47173. this._targetedAnimations = [];
  47174. this._animatables = [];
  47175. var index = this._scene.animationGroups.indexOf(this);
  47176. if (index > -1) {
  47177. this._scene.animationGroups.splice(index, 1);
  47178. }
  47179. };
  47180. return AnimationGroup;
  47181. }());
  47182. BABYLON.AnimationGroup = AnimationGroup;
  47183. })(BABYLON || (BABYLON = {}));
  47184. //# sourceMappingURL=babylon.animationGroup.js.map
  47185. var BABYLON;
  47186. (function (BABYLON) {
  47187. var RuntimeAnimation = /** @class */ (function () {
  47188. function RuntimeAnimation(target, animation) {
  47189. this._offsetsCache = {};
  47190. this._highLimitsCache = {};
  47191. this._stopped = false;
  47192. this._blendingFactor = 0;
  47193. this._ratioOffset = 0;
  47194. this._animation = animation;
  47195. this._target = target;
  47196. animation._runtimeAnimations.push(this);
  47197. }
  47198. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47199. get: function () {
  47200. return this._animation;
  47201. },
  47202. enumerable: true,
  47203. configurable: true
  47204. });
  47205. RuntimeAnimation.prototype.reset = function () {
  47206. this._offsetsCache = {};
  47207. this._highLimitsCache = {};
  47208. this.currentFrame = 0;
  47209. this._blendingFactor = 0;
  47210. this._originalBlendValue = null;
  47211. };
  47212. RuntimeAnimation.prototype.isStopped = function () {
  47213. return this._stopped;
  47214. };
  47215. RuntimeAnimation.prototype.dispose = function () {
  47216. var index = this._animation.runtimeAnimations.indexOf(this);
  47217. if (index > -1) {
  47218. this._animation.runtimeAnimations.splice(index, 1);
  47219. }
  47220. };
  47221. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47222. if (typeof value === "function") {
  47223. return value();
  47224. }
  47225. return value;
  47226. };
  47227. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47228. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47229. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47230. }
  47231. this.currentFrame = currentFrame;
  47232. var keys = this._animation.getKeys();
  47233. // Try to get a hash to find the right key
  47234. 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));
  47235. if (keys[startKeyIndex].frame >= currentFrame) {
  47236. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47237. startKeyIndex--;
  47238. }
  47239. }
  47240. for (var key = startKeyIndex; key < keys.length; key++) {
  47241. var endKey = keys[key + 1];
  47242. if (endKey.frame >= currentFrame) {
  47243. var startKey = keys[key];
  47244. var startValue = this._getKeyValue(startKey.value);
  47245. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47246. return startValue;
  47247. }
  47248. var endValue = this._getKeyValue(endKey.value);
  47249. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47250. var frameDelta = endKey.frame - startKey.frame;
  47251. // gradient : percent of currentFrame between the frame inf and the frame sup
  47252. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47253. // check for easingFunction and correction of gradient
  47254. var easingFunction = this._animation.getEasingFunction();
  47255. if (easingFunction != null) {
  47256. gradient = easingFunction.ease(gradient);
  47257. }
  47258. switch (this._animation.dataType) {
  47259. // Float
  47260. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47261. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47262. switch (loopMode) {
  47263. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47264. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47265. return floatValue;
  47266. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47267. return offsetValue * repeatCount + floatValue;
  47268. }
  47269. break;
  47270. // Quaternion
  47271. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47272. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47273. switch (loopMode) {
  47274. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47275. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47276. return quatValue;
  47277. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47278. return quatValue.add(offsetValue.scale(repeatCount));
  47279. }
  47280. return quatValue;
  47281. // Vector3
  47282. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47283. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47284. switch (loopMode) {
  47285. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47286. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47287. return vec3Value;
  47288. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47289. return vec3Value.add(offsetValue.scale(repeatCount));
  47290. }
  47291. // Vector2
  47292. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47293. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47294. switch (loopMode) {
  47295. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47296. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47297. return vec2Value;
  47298. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47299. return vec2Value.add(offsetValue.scale(repeatCount));
  47300. }
  47301. // Size
  47302. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47303. switch (loopMode) {
  47304. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47305. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47306. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47307. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47308. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47309. }
  47310. // Color3
  47311. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47312. switch (loopMode) {
  47313. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47314. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47315. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47316. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47317. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47318. }
  47319. // Matrix
  47320. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47321. switch (loopMode) {
  47322. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47323. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47324. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47325. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47326. }
  47327. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47328. return startValue;
  47329. }
  47330. default:
  47331. break;
  47332. }
  47333. break;
  47334. }
  47335. }
  47336. return this._getKeyValue(keys[keys.length - 1].value);
  47337. };
  47338. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47339. if (blend === void 0) { blend = false; }
  47340. // Set value
  47341. var path;
  47342. var destination;
  47343. var targetPropertyPath = this._animation.targetPropertyPath;
  47344. if (targetPropertyPath.length > 1) {
  47345. var property = this._target[targetPropertyPath[0]];
  47346. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47347. property = property[targetPropertyPath[index]];
  47348. }
  47349. path = targetPropertyPath[targetPropertyPath.length - 1];
  47350. destination = property;
  47351. }
  47352. else {
  47353. path = targetPropertyPath[0];
  47354. destination = this._target;
  47355. }
  47356. // Blending
  47357. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47358. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47359. if (enableBlending && this._blendingFactor <= 1.0) {
  47360. if (!this._originalBlendValue) {
  47361. if (destination[path].clone) {
  47362. this._originalBlendValue = destination[path].clone();
  47363. }
  47364. else {
  47365. this._originalBlendValue = destination[path];
  47366. }
  47367. }
  47368. if (this._originalBlendValue.prototype) {
  47369. if (this._originalBlendValue.prototype.Lerp) {
  47370. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47371. }
  47372. else {
  47373. destination[path] = currentValue;
  47374. }
  47375. }
  47376. else if (this._originalBlendValue.m) {
  47377. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47378. }
  47379. else {
  47380. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47381. }
  47382. this._blendingFactor += blendingSpeed;
  47383. }
  47384. else {
  47385. destination[path] = currentValue;
  47386. }
  47387. if (this._target.markAsDirty) {
  47388. this._target.markAsDirty(this._animation.targetProperty);
  47389. }
  47390. };
  47391. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47392. if (this._target && this._target.animationPropertiesOverride) {
  47393. return this._target.animationPropertiesOverride.loopMode;
  47394. }
  47395. return this._animation.loopMode;
  47396. };
  47397. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47398. var keys = this._animation.getKeys();
  47399. if (frame < keys[0].frame) {
  47400. frame = keys[0].frame;
  47401. }
  47402. else if (frame > keys[keys.length - 1].frame) {
  47403. frame = keys[keys.length - 1].frame;
  47404. }
  47405. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47406. this.setValue(currentValue);
  47407. };
  47408. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47409. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47410. this._ratioOffset = this._previousRatio - newRatio;
  47411. };
  47412. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47413. if (blend === void 0) { blend = false; }
  47414. var targetPropertyPath = this._animation.targetPropertyPath;
  47415. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47416. this._stopped = true;
  47417. return false;
  47418. }
  47419. var returnValue = true;
  47420. var keys = this._animation.getKeys();
  47421. // Adding a start key at frame 0 if missing
  47422. if (keys[0].frame !== 0) {
  47423. var newKey = { frame: 0, value: keys[0].value };
  47424. keys.splice(0, 0, newKey);
  47425. }
  47426. // Check limits
  47427. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47428. from = keys[0].frame;
  47429. }
  47430. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47431. to = keys[keys.length - 1].frame;
  47432. }
  47433. //to and from cannot be the same key
  47434. if (from === to) {
  47435. if (from > keys[0].frame) {
  47436. from--;
  47437. }
  47438. else if (to < keys[keys.length - 1].frame) {
  47439. to++;
  47440. }
  47441. }
  47442. // Compute ratio
  47443. var range = to - from;
  47444. var offsetValue;
  47445. // ratio represents the frame delta between from and to
  47446. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47447. var highLimitValue = 0;
  47448. this._previousDelay = delay;
  47449. this._previousRatio = ratio;
  47450. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47451. returnValue = false;
  47452. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47453. }
  47454. else {
  47455. // Get max value if required
  47456. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47457. var keyOffset = to.toString() + from.toString();
  47458. if (!this._offsetsCache[keyOffset]) {
  47459. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47460. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47461. switch (this._animation.dataType) {
  47462. // Float
  47463. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47464. this._offsetsCache[keyOffset] = toValue - fromValue;
  47465. break;
  47466. // Quaternion
  47467. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47468. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47469. break;
  47470. // Vector3
  47471. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47472. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47473. // Vector2
  47474. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47475. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47476. // Size
  47477. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47478. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47479. // Color3
  47480. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47481. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47482. default:
  47483. break;
  47484. }
  47485. this._highLimitsCache[keyOffset] = toValue;
  47486. }
  47487. highLimitValue = this._highLimitsCache[keyOffset];
  47488. offsetValue = this._offsetsCache[keyOffset];
  47489. }
  47490. }
  47491. if (offsetValue === undefined) {
  47492. switch (this._animation.dataType) {
  47493. // Float
  47494. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47495. offsetValue = 0;
  47496. break;
  47497. // Quaternion
  47498. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47499. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47500. break;
  47501. // Vector3
  47502. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47503. offsetValue = BABYLON.Vector3.Zero();
  47504. break;
  47505. // Vector2
  47506. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47507. offsetValue = BABYLON.Vector2.Zero();
  47508. break;
  47509. // Size
  47510. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47511. offsetValue = BABYLON.Size.Zero();
  47512. break;
  47513. // Color3
  47514. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47515. offsetValue = BABYLON.Color3.Black();
  47516. }
  47517. }
  47518. // Compute value
  47519. var repeatCount = (ratio / range) >> 0;
  47520. var currentFrame = returnValue ? from + ratio % range : to;
  47521. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47522. // Set value
  47523. this.setValue(currentValue);
  47524. // Check events
  47525. var events = this._animation.getEvents();
  47526. for (var index = 0; index < events.length; index++) {
  47527. // Make sure current frame has passed event frame and that event frame is within the current range
  47528. // Also, handle both forward and reverse animations
  47529. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47530. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47531. var event = events[index];
  47532. if (!event.isDone) {
  47533. // If event should be done only once, remove it.
  47534. if (event.onlyOnce) {
  47535. events.splice(index, 1);
  47536. index--;
  47537. }
  47538. event.isDone = true;
  47539. event.action();
  47540. } // Don't do anything if the event has already be done.
  47541. }
  47542. else if (events[index].isDone && !events[index].onlyOnce) {
  47543. // reset event, the animation is looping
  47544. events[index].isDone = false;
  47545. }
  47546. }
  47547. if (!returnValue) {
  47548. this._stopped = true;
  47549. }
  47550. return returnValue;
  47551. };
  47552. return RuntimeAnimation;
  47553. }());
  47554. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47555. })(BABYLON || (BABYLON = {}));
  47556. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47557. var BABYLON;
  47558. (function (BABYLON) {
  47559. var Animatable = /** @class */ (function () {
  47560. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47561. if (fromFrame === void 0) { fromFrame = 0; }
  47562. if (toFrame === void 0) { toFrame = 100; }
  47563. if (loopAnimation === void 0) { loopAnimation = false; }
  47564. if (speedRatio === void 0) { speedRatio = 1.0; }
  47565. this.target = target;
  47566. this.fromFrame = fromFrame;
  47567. this.toFrame = toFrame;
  47568. this.loopAnimation = loopAnimation;
  47569. this.onAnimationEnd = onAnimationEnd;
  47570. this._localDelayOffset = null;
  47571. this._pausedDelay = null;
  47572. this._runtimeAnimations = new Array();
  47573. this._paused = false;
  47574. this._speedRatio = 1;
  47575. this.animationStarted = false;
  47576. if (animations) {
  47577. this.appendAnimations(target, animations);
  47578. }
  47579. this._speedRatio = speedRatio;
  47580. this._scene = scene;
  47581. scene._activeAnimatables.push(this);
  47582. }
  47583. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47584. get: function () {
  47585. return this._speedRatio;
  47586. },
  47587. set: function (value) {
  47588. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47589. var animation = this._runtimeAnimations[index];
  47590. animation._prepareForSpeedRatioChange(value);
  47591. }
  47592. this._speedRatio = value;
  47593. },
  47594. enumerable: true,
  47595. configurable: true
  47596. });
  47597. // Methods
  47598. Animatable.prototype.getAnimations = function () {
  47599. return this._runtimeAnimations;
  47600. };
  47601. Animatable.prototype.appendAnimations = function (target, animations) {
  47602. for (var index = 0; index < animations.length; index++) {
  47603. var animation = animations[index];
  47604. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47605. }
  47606. };
  47607. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47608. var runtimeAnimations = this._runtimeAnimations;
  47609. for (var index = 0; index < runtimeAnimations.length; index++) {
  47610. if (runtimeAnimations[index].animation.targetProperty === property) {
  47611. return runtimeAnimations[index].animation;
  47612. }
  47613. }
  47614. return null;
  47615. };
  47616. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47617. var runtimeAnimations = this._runtimeAnimations;
  47618. for (var index = 0; index < runtimeAnimations.length; index++) {
  47619. if (runtimeAnimations[index].animation.targetProperty === property) {
  47620. return runtimeAnimations[index];
  47621. }
  47622. }
  47623. return null;
  47624. };
  47625. Animatable.prototype.reset = function () {
  47626. var runtimeAnimations = this._runtimeAnimations;
  47627. for (var index = 0; index < runtimeAnimations.length; index++) {
  47628. runtimeAnimations[index].reset();
  47629. }
  47630. // Reset to original value
  47631. for (index = 0; index < runtimeAnimations.length; index++) {
  47632. var animation = runtimeAnimations[index];
  47633. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47634. }
  47635. this._localDelayOffset = null;
  47636. this._pausedDelay = null;
  47637. };
  47638. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47639. var runtimeAnimations = this._runtimeAnimations;
  47640. for (var index = 0; index < runtimeAnimations.length; index++) {
  47641. runtimeAnimations[index].animation.enableBlending = true;
  47642. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47643. }
  47644. };
  47645. Animatable.prototype.disableBlending = function () {
  47646. var runtimeAnimations = this._runtimeAnimations;
  47647. for (var index = 0; index < runtimeAnimations.length; index++) {
  47648. runtimeAnimations[index].animation.enableBlending = false;
  47649. }
  47650. };
  47651. Animatable.prototype.goToFrame = function (frame) {
  47652. var runtimeAnimations = this._runtimeAnimations;
  47653. if (runtimeAnimations[0]) {
  47654. var fps = runtimeAnimations[0].animation.framePerSecond;
  47655. var currentFrame = runtimeAnimations[0].currentFrame;
  47656. var adjustTime = frame - currentFrame;
  47657. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47658. if (this._localDelayOffset === null) {
  47659. this._localDelayOffset = 0;
  47660. }
  47661. this._localDelayOffset -= delay;
  47662. }
  47663. for (var index = 0; index < runtimeAnimations.length; index++) {
  47664. runtimeAnimations[index].goToFrame(frame);
  47665. }
  47666. };
  47667. Animatable.prototype.pause = function () {
  47668. if (this._paused) {
  47669. return;
  47670. }
  47671. this._paused = true;
  47672. };
  47673. Animatable.prototype.restart = function () {
  47674. this._paused = false;
  47675. };
  47676. Animatable.prototype.stop = function (animationName) {
  47677. if (animationName) {
  47678. var idx = this._scene._activeAnimatables.indexOf(this);
  47679. if (idx > -1) {
  47680. var runtimeAnimations = this._runtimeAnimations;
  47681. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47682. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47683. continue;
  47684. }
  47685. runtimeAnimations[index].dispose();
  47686. runtimeAnimations.splice(index, 1);
  47687. }
  47688. if (runtimeAnimations.length == 0) {
  47689. this._scene._activeAnimatables.splice(idx, 1);
  47690. if (this.onAnimationEnd) {
  47691. this.onAnimationEnd();
  47692. }
  47693. }
  47694. }
  47695. }
  47696. else {
  47697. var index = this._scene._activeAnimatables.indexOf(this);
  47698. if (index > -1) {
  47699. this._scene._activeAnimatables.splice(index, 1);
  47700. var runtimeAnimations = this._runtimeAnimations;
  47701. for (var index = 0; index < runtimeAnimations.length; index++) {
  47702. runtimeAnimations[index].dispose();
  47703. }
  47704. if (this.onAnimationEnd) {
  47705. this.onAnimationEnd();
  47706. }
  47707. }
  47708. }
  47709. };
  47710. Animatable.prototype._animate = function (delay) {
  47711. if (this._paused) {
  47712. this.animationStarted = false;
  47713. if (this._pausedDelay === null) {
  47714. this._pausedDelay = delay;
  47715. }
  47716. return true;
  47717. }
  47718. if (this._localDelayOffset === null) {
  47719. this._localDelayOffset = delay;
  47720. this._pausedDelay = null;
  47721. }
  47722. else if (this._pausedDelay !== null) {
  47723. this._localDelayOffset += delay - this._pausedDelay;
  47724. this._pausedDelay = null;
  47725. }
  47726. // Animating
  47727. var running = false;
  47728. var runtimeAnimations = this._runtimeAnimations;
  47729. var index;
  47730. for (index = 0; index < runtimeAnimations.length; index++) {
  47731. var animation = runtimeAnimations[index];
  47732. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47733. running = running || isRunning;
  47734. }
  47735. this.animationStarted = running;
  47736. if (!running) {
  47737. // Remove from active animatables
  47738. index = this._scene._activeAnimatables.indexOf(this);
  47739. this._scene._activeAnimatables.splice(index, 1);
  47740. // Dispose all runtime animations
  47741. for (index = 0; index < runtimeAnimations.length; index++) {
  47742. runtimeAnimations[index].dispose();
  47743. }
  47744. }
  47745. if (!running && this.onAnimationEnd) {
  47746. this.onAnimationEnd();
  47747. this.onAnimationEnd = null;
  47748. }
  47749. return running;
  47750. };
  47751. return Animatable;
  47752. }());
  47753. BABYLON.Animatable = Animatable;
  47754. })(BABYLON || (BABYLON = {}));
  47755. //# sourceMappingURL=babylon.animatable.js.map
  47756. var BABYLON;
  47757. (function (BABYLON) {
  47758. var EasingFunction = /** @class */ (function () {
  47759. function EasingFunction() {
  47760. // Properties
  47761. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47762. }
  47763. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47764. get: function () {
  47765. return EasingFunction._EASINGMODE_EASEIN;
  47766. },
  47767. enumerable: true,
  47768. configurable: true
  47769. });
  47770. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47771. get: function () {
  47772. return EasingFunction._EASINGMODE_EASEOUT;
  47773. },
  47774. enumerable: true,
  47775. configurable: true
  47776. });
  47777. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47778. get: function () {
  47779. return EasingFunction._EASINGMODE_EASEINOUT;
  47780. },
  47781. enumerable: true,
  47782. configurable: true
  47783. });
  47784. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47785. var n = Math.min(Math.max(easingMode, 0), 2);
  47786. this._easingMode = n;
  47787. };
  47788. EasingFunction.prototype.getEasingMode = function () {
  47789. return this._easingMode;
  47790. };
  47791. EasingFunction.prototype.easeInCore = function (gradient) {
  47792. throw new Error('You must implement this method');
  47793. };
  47794. EasingFunction.prototype.ease = function (gradient) {
  47795. switch (this._easingMode) {
  47796. case EasingFunction.EASINGMODE_EASEIN:
  47797. return this.easeInCore(gradient);
  47798. case EasingFunction.EASINGMODE_EASEOUT:
  47799. return (1 - this.easeInCore(1 - gradient));
  47800. }
  47801. if (gradient >= 0.5) {
  47802. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47803. }
  47804. return (this.easeInCore(gradient * 2) * 0.5);
  47805. };
  47806. //Statics
  47807. EasingFunction._EASINGMODE_EASEIN = 0;
  47808. EasingFunction._EASINGMODE_EASEOUT = 1;
  47809. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47810. return EasingFunction;
  47811. }());
  47812. BABYLON.EasingFunction = EasingFunction;
  47813. var CircleEase = /** @class */ (function (_super) {
  47814. __extends(CircleEase, _super);
  47815. function CircleEase() {
  47816. return _super !== null && _super.apply(this, arguments) || this;
  47817. }
  47818. CircleEase.prototype.easeInCore = function (gradient) {
  47819. gradient = Math.max(0, Math.min(1, gradient));
  47820. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47821. };
  47822. return CircleEase;
  47823. }(EasingFunction));
  47824. BABYLON.CircleEase = CircleEase;
  47825. var BackEase = /** @class */ (function (_super) {
  47826. __extends(BackEase, _super);
  47827. function BackEase(amplitude) {
  47828. if (amplitude === void 0) { amplitude = 1; }
  47829. var _this = _super.call(this) || this;
  47830. _this.amplitude = amplitude;
  47831. return _this;
  47832. }
  47833. BackEase.prototype.easeInCore = function (gradient) {
  47834. var num = Math.max(0, this.amplitude);
  47835. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47836. };
  47837. return BackEase;
  47838. }(EasingFunction));
  47839. BABYLON.BackEase = BackEase;
  47840. var BounceEase = /** @class */ (function (_super) {
  47841. __extends(BounceEase, _super);
  47842. function BounceEase(bounces, bounciness) {
  47843. if (bounces === void 0) { bounces = 3; }
  47844. if (bounciness === void 0) { bounciness = 2; }
  47845. var _this = _super.call(this) || this;
  47846. _this.bounces = bounces;
  47847. _this.bounciness = bounciness;
  47848. return _this;
  47849. }
  47850. BounceEase.prototype.easeInCore = function (gradient) {
  47851. var y = Math.max(0.0, this.bounces);
  47852. var bounciness = this.bounciness;
  47853. if (bounciness <= 1.0) {
  47854. bounciness = 1.001;
  47855. }
  47856. var num9 = Math.pow(bounciness, y);
  47857. var num5 = 1.0 - bounciness;
  47858. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47859. var num15 = gradient * num4;
  47860. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47861. var num3 = Math.floor(num65);
  47862. var num13 = num3 + 1.0;
  47863. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47864. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47865. var num7 = (num8 + num12) * 0.5;
  47866. var num6 = gradient - num7;
  47867. var num2 = num7 - num8;
  47868. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47869. };
  47870. return BounceEase;
  47871. }(EasingFunction));
  47872. BABYLON.BounceEase = BounceEase;
  47873. var CubicEase = /** @class */ (function (_super) {
  47874. __extends(CubicEase, _super);
  47875. function CubicEase() {
  47876. return _super !== null && _super.apply(this, arguments) || this;
  47877. }
  47878. CubicEase.prototype.easeInCore = function (gradient) {
  47879. return (gradient * gradient * gradient);
  47880. };
  47881. return CubicEase;
  47882. }(EasingFunction));
  47883. BABYLON.CubicEase = CubicEase;
  47884. var ElasticEase = /** @class */ (function (_super) {
  47885. __extends(ElasticEase, _super);
  47886. function ElasticEase(oscillations, springiness) {
  47887. if (oscillations === void 0) { oscillations = 3; }
  47888. if (springiness === void 0) { springiness = 3; }
  47889. var _this = _super.call(this) || this;
  47890. _this.oscillations = oscillations;
  47891. _this.springiness = springiness;
  47892. return _this;
  47893. }
  47894. ElasticEase.prototype.easeInCore = function (gradient) {
  47895. var num2;
  47896. var num3 = Math.max(0.0, this.oscillations);
  47897. var num = Math.max(0.0, this.springiness);
  47898. if (num == 0) {
  47899. num2 = gradient;
  47900. }
  47901. else {
  47902. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47903. }
  47904. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47905. };
  47906. return ElasticEase;
  47907. }(EasingFunction));
  47908. BABYLON.ElasticEase = ElasticEase;
  47909. var ExponentialEase = /** @class */ (function (_super) {
  47910. __extends(ExponentialEase, _super);
  47911. function ExponentialEase(exponent) {
  47912. if (exponent === void 0) { exponent = 2; }
  47913. var _this = _super.call(this) || this;
  47914. _this.exponent = exponent;
  47915. return _this;
  47916. }
  47917. ExponentialEase.prototype.easeInCore = function (gradient) {
  47918. if (this.exponent <= 0) {
  47919. return gradient;
  47920. }
  47921. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47922. };
  47923. return ExponentialEase;
  47924. }(EasingFunction));
  47925. BABYLON.ExponentialEase = ExponentialEase;
  47926. var PowerEase = /** @class */ (function (_super) {
  47927. __extends(PowerEase, _super);
  47928. function PowerEase(power) {
  47929. if (power === void 0) { power = 2; }
  47930. var _this = _super.call(this) || this;
  47931. _this.power = power;
  47932. return _this;
  47933. }
  47934. PowerEase.prototype.easeInCore = function (gradient) {
  47935. var y = Math.max(0.0, this.power);
  47936. return Math.pow(gradient, y);
  47937. };
  47938. return PowerEase;
  47939. }(EasingFunction));
  47940. BABYLON.PowerEase = PowerEase;
  47941. var QuadraticEase = /** @class */ (function (_super) {
  47942. __extends(QuadraticEase, _super);
  47943. function QuadraticEase() {
  47944. return _super !== null && _super.apply(this, arguments) || this;
  47945. }
  47946. QuadraticEase.prototype.easeInCore = function (gradient) {
  47947. return (gradient * gradient);
  47948. };
  47949. return QuadraticEase;
  47950. }(EasingFunction));
  47951. BABYLON.QuadraticEase = QuadraticEase;
  47952. var QuarticEase = /** @class */ (function (_super) {
  47953. __extends(QuarticEase, _super);
  47954. function QuarticEase() {
  47955. return _super !== null && _super.apply(this, arguments) || this;
  47956. }
  47957. QuarticEase.prototype.easeInCore = function (gradient) {
  47958. return (gradient * gradient * gradient * gradient);
  47959. };
  47960. return QuarticEase;
  47961. }(EasingFunction));
  47962. BABYLON.QuarticEase = QuarticEase;
  47963. var QuinticEase = /** @class */ (function (_super) {
  47964. __extends(QuinticEase, _super);
  47965. function QuinticEase() {
  47966. return _super !== null && _super.apply(this, arguments) || this;
  47967. }
  47968. QuinticEase.prototype.easeInCore = function (gradient) {
  47969. return (gradient * gradient * gradient * gradient * gradient);
  47970. };
  47971. return QuinticEase;
  47972. }(EasingFunction));
  47973. BABYLON.QuinticEase = QuinticEase;
  47974. var SineEase = /** @class */ (function (_super) {
  47975. __extends(SineEase, _super);
  47976. function SineEase() {
  47977. return _super !== null && _super.apply(this, arguments) || this;
  47978. }
  47979. SineEase.prototype.easeInCore = function (gradient) {
  47980. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47981. };
  47982. return SineEase;
  47983. }(EasingFunction));
  47984. BABYLON.SineEase = SineEase;
  47985. var BezierCurveEase = /** @class */ (function (_super) {
  47986. __extends(BezierCurveEase, _super);
  47987. function BezierCurveEase(x1, y1, x2, y2) {
  47988. if (x1 === void 0) { x1 = 0; }
  47989. if (y1 === void 0) { y1 = 0; }
  47990. if (x2 === void 0) { x2 = 1; }
  47991. if (y2 === void 0) { y2 = 1; }
  47992. var _this = _super.call(this) || this;
  47993. _this.x1 = x1;
  47994. _this.y1 = y1;
  47995. _this.x2 = x2;
  47996. _this.y2 = y2;
  47997. return _this;
  47998. }
  47999. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48000. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48001. };
  48002. return BezierCurveEase;
  48003. }(EasingFunction));
  48004. BABYLON.BezierCurveEase = BezierCurveEase;
  48005. })(BABYLON || (BABYLON = {}));
  48006. //# sourceMappingURL=babylon.easing.js.map
  48007. var BABYLON;
  48008. (function (BABYLON) {
  48009. var Condition = /** @class */ (function () {
  48010. function Condition(actionManager) {
  48011. this._actionManager = actionManager;
  48012. }
  48013. Condition.prototype.isValid = function () {
  48014. return true;
  48015. };
  48016. Condition.prototype._getProperty = function (propertyPath) {
  48017. return this._actionManager._getProperty(propertyPath);
  48018. };
  48019. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48020. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48021. };
  48022. Condition.prototype.serialize = function () {
  48023. };
  48024. Condition.prototype._serialize = function (serializedCondition) {
  48025. return {
  48026. type: 2,
  48027. children: [],
  48028. name: serializedCondition.name,
  48029. properties: serializedCondition.properties
  48030. };
  48031. };
  48032. return Condition;
  48033. }());
  48034. BABYLON.Condition = Condition;
  48035. var ValueCondition = /** @class */ (function (_super) {
  48036. __extends(ValueCondition, _super);
  48037. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48038. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48039. var _this = _super.call(this, actionManager) || this;
  48040. _this.propertyPath = propertyPath;
  48041. _this.value = value;
  48042. _this.operator = operator;
  48043. _this._target = target;
  48044. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48045. _this._property = _this._getProperty(_this.propertyPath);
  48046. return _this;
  48047. }
  48048. Object.defineProperty(ValueCondition, "IsEqual", {
  48049. get: function () {
  48050. return ValueCondition._IsEqual;
  48051. },
  48052. enumerable: true,
  48053. configurable: true
  48054. });
  48055. Object.defineProperty(ValueCondition, "IsDifferent", {
  48056. get: function () {
  48057. return ValueCondition._IsDifferent;
  48058. },
  48059. enumerable: true,
  48060. configurable: true
  48061. });
  48062. Object.defineProperty(ValueCondition, "IsGreater", {
  48063. get: function () {
  48064. return ValueCondition._IsGreater;
  48065. },
  48066. enumerable: true,
  48067. configurable: true
  48068. });
  48069. Object.defineProperty(ValueCondition, "IsLesser", {
  48070. get: function () {
  48071. return ValueCondition._IsLesser;
  48072. },
  48073. enumerable: true,
  48074. configurable: true
  48075. });
  48076. // Methods
  48077. ValueCondition.prototype.isValid = function () {
  48078. switch (this.operator) {
  48079. case ValueCondition.IsGreater:
  48080. return this._effectiveTarget[this._property] > this.value;
  48081. case ValueCondition.IsLesser:
  48082. return this._effectiveTarget[this._property] < this.value;
  48083. case ValueCondition.IsEqual:
  48084. case ValueCondition.IsDifferent:
  48085. var check;
  48086. if (this.value.equals) {
  48087. check = this.value.equals(this._effectiveTarget[this._property]);
  48088. }
  48089. else {
  48090. check = this.value === this._effectiveTarget[this._property];
  48091. }
  48092. return this.operator === ValueCondition.IsEqual ? check : !check;
  48093. }
  48094. return false;
  48095. };
  48096. ValueCondition.prototype.serialize = function () {
  48097. return this._serialize({
  48098. name: "ValueCondition",
  48099. properties: [
  48100. BABYLON.Action._GetTargetProperty(this._target),
  48101. { name: "propertyPath", value: this.propertyPath },
  48102. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48103. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48104. ]
  48105. });
  48106. };
  48107. ValueCondition.GetOperatorName = function (operator) {
  48108. switch (operator) {
  48109. case ValueCondition._IsEqual: return "IsEqual";
  48110. case ValueCondition._IsDifferent: return "IsDifferent";
  48111. case ValueCondition._IsGreater: return "IsGreater";
  48112. case ValueCondition._IsLesser: return "IsLesser";
  48113. default: return "";
  48114. }
  48115. };
  48116. // Statics
  48117. ValueCondition._IsEqual = 0;
  48118. ValueCondition._IsDifferent = 1;
  48119. ValueCondition._IsGreater = 2;
  48120. ValueCondition._IsLesser = 3;
  48121. return ValueCondition;
  48122. }(Condition));
  48123. BABYLON.ValueCondition = ValueCondition;
  48124. var PredicateCondition = /** @class */ (function (_super) {
  48125. __extends(PredicateCondition, _super);
  48126. function PredicateCondition(actionManager, predicate) {
  48127. var _this = _super.call(this, actionManager) || this;
  48128. _this.predicate = predicate;
  48129. return _this;
  48130. }
  48131. PredicateCondition.prototype.isValid = function () {
  48132. return this.predicate();
  48133. };
  48134. return PredicateCondition;
  48135. }(Condition));
  48136. BABYLON.PredicateCondition = PredicateCondition;
  48137. var StateCondition = /** @class */ (function (_super) {
  48138. __extends(StateCondition, _super);
  48139. function StateCondition(actionManager, target, value) {
  48140. var _this = _super.call(this, actionManager) || this;
  48141. _this.value = value;
  48142. _this._target = target;
  48143. return _this;
  48144. }
  48145. // Methods
  48146. StateCondition.prototype.isValid = function () {
  48147. return this._target.state === this.value;
  48148. };
  48149. StateCondition.prototype.serialize = function () {
  48150. return this._serialize({
  48151. name: "StateCondition",
  48152. properties: [
  48153. BABYLON.Action._GetTargetProperty(this._target),
  48154. { name: "value", value: this.value }
  48155. ]
  48156. });
  48157. };
  48158. return StateCondition;
  48159. }(Condition));
  48160. BABYLON.StateCondition = StateCondition;
  48161. })(BABYLON || (BABYLON = {}));
  48162. //# sourceMappingURL=babylon.condition.js.map
  48163. var BABYLON;
  48164. (function (BABYLON) {
  48165. var Action = /** @class */ (function () {
  48166. function Action(triggerOptions, condition) {
  48167. this.triggerOptions = triggerOptions;
  48168. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48169. if (triggerOptions.parameter) {
  48170. this.trigger = triggerOptions.trigger;
  48171. this._triggerParameter = triggerOptions.parameter;
  48172. }
  48173. else {
  48174. this.trigger = triggerOptions;
  48175. }
  48176. this._nextActiveAction = this;
  48177. this._condition = condition;
  48178. }
  48179. // Methods
  48180. Action.prototype._prepare = function () {
  48181. };
  48182. Action.prototype.getTriggerParameter = function () {
  48183. return this._triggerParameter;
  48184. };
  48185. Action.prototype._executeCurrent = function (evt) {
  48186. if (this._nextActiveAction._condition) {
  48187. var condition = this._nextActiveAction._condition;
  48188. var currentRenderId = this._actionManager.getScene().getRenderId();
  48189. // We cache the current evaluation for the current frame
  48190. if (condition._evaluationId === currentRenderId) {
  48191. if (!condition._currentResult) {
  48192. return;
  48193. }
  48194. }
  48195. else {
  48196. condition._evaluationId = currentRenderId;
  48197. if (!condition.isValid()) {
  48198. condition._currentResult = false;
  48199. return;
  48200. }
  48201. condition._currentResult = true;
  48202. }
  48203. }
  48204. this.onBeforeExecuteObservable.notifyObservers(this);
  48205. this._nextActiveAction.execute(evt);
  48206. this.skipToNextActiveAction();
  48207. };
  48208. Action.prototype.execute = function (evt) {
  48209. };
  48210. Action.prototype.skipToNextActiveAction = function () {
  48211. if (this._nextActiveAction._child) {
  48212. if (!this._nextActiveAction._child._actionManager) {
  48213. this._nextActiveAction._child._actionManager = this._actionManager;
  48214. }
  48215. this._nextActiveAction = this._nextActiveAction._child;
  48216. }
  48217. else {
  48218. this._nextActiveAction = this;
  48219. }
  48220. };
  48221. Action.prototype.then = function (action) {
  48222. this._child = action;
  48223. action._actionManager = this._actionManager;
  48224. action._prepare();
  48225. return action;
  48226. };
  48227. Action.prototype._getProperty = function (propertyPath) {
  48228. return this._actionManager._getProperty(propertyPath);
  48229. };
  48230. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48231. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48232. };
  48233. Action.prototype.serialize = function (parent) {
  48234. };
  48235. // Called by BABYLON.Action objects in serialize(...). Internal use
  48236. Action.prototype._serialize = function (serializedAction, parent) {
  48237. var serializationObject = {
  48238. type: 1,
  48239. children: [],
  48240. name: serializedAction.name,
  48241. properties: serializedAction.properties || []
  48242. };
  48243. // Serialize child
  48244. if (this._child) {
  48245. this._child.serialize(serializationObject);
  48246. }
  48247. // Check if "this" has a condition
  48248. if (this._condition) {
  48249. var serializedCondition = this._condition.serialize();
  48250. serializedCondition.children.push(serializationObject);
  48251. if (parent) {
  48252. parent.children.push(serializedCondition);
  48253. }
  48254. return serializedCondition;
  48255. }
  48256. if (parent) {
  48257. parent.children.push(serializationObject);
  48258. }
  48259. return serializationObject;
  48260. };
  48261. Action._SerializeValueAsString = function (value) {
  48262. if (typeof value === "number") {
  48263. return value.toString();
  48264. }
  48265. if (typeof value === "boolean") {
  48266. return value ? "true" : "false";
  48267. }
  48268. if (value instanceof BABYLON.Vector2) {
  48269. return value.x + ", " + value.y;
  48270. }
  48271. if (value instanceof BABYLON.Vector3) {
  48272. return value.x + ", " + value.y + ", " + value.z;
  48273. }
  48274. if (value instanceof BABYLON.Color3) {
  48275. return value.r + ", " + value.g + ", " + value.b;
  48276. }
  48277. if (value instanceof BABYLON.Color4) {
  48278. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48279. }
  48280. return value; // string
  48281. };
  48282. Action._GetTargetProperty = function (target) {
  48283. return {
  48284. name: "target",
  48285. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48286. : target instanceof BABYLON.Light ? "LightProperties"
  48287. : target instanceof BABYLON.Camera ? "CameraProperties"
  48288. : "SceneProperties",
  48289. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48290. };
  48291. };
  48292. return Action;
  48293. }());
  48294. BABYLON.Action = Action;
  48295. })(BABYLON || (BABYLON = {}));
  48296. //# sourceMappingURL=babylon.action.js.map
  48297. var BABYLON;
  48298. (function (BABYLON) {
  48299. /**
  48300. * ActionEvent is the event beint sent when an action is triggered.
  48301. */
  48302. var ActionEvent = /** @class */ (function () {
  48303. /**
  48304. * @param source The mesh or sprite that triggered the action.
  48305. * @param pointerX The X mouse cursor position at the time of the event
  48306. * @param pointerY The Y mouse cursor position at the time of the event
  48307. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48308. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48309. */
  48310. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48311. this.source = source;
  48312. this.pointerX = pointerX;
  48313. this.pointerY = pointerY;
  48314. this.meshUnderPointer = meshUnderPointer;
  48315. this.sourceEvent = sourceEvent;
  48316. this.additionalData = additionalData;
  48317. }
  48318. /**
  48319. * Helper function to auto-create an ActionEvent from a source mesh.
  48320. * @param source The source mesh that triggered the event
  48321. * @param evt {Event} The original (browser) event
  48322. */
  48323. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48324. var scene = source.getScene();
  48325. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48326. };
  48327. /**
  48328. * Helper function to auto-create an ActionEvent from a source mesh.
  48329. * @param source The source sprite that triggered the event
  48330. * @param scene Scene associated with the sprite
  48331. * @param evt {Event} The original (browser) event
  48332. */
  48333. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48334. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48335. };
  48336. /**
  48337. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48338. * @param scene the scene where the event occurred
  48339. * @param evt {Event} The original (browser) event
  48340. */
  48341. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48342. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48343. };
  48344. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48345. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48346. };
  48347. return ActionEvent;
  48348. }());
  48349. BABYLON.ActionEvent = ActionEvent;
  48350. /**
  48351. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48352. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48353. */
  48354. var ActionManager = /** @class */ (function () {
  48355. function ActionManager(scene) {
  48356. // Members
  48357. this.actions = new Array();
  48358. this.hoverCursor = '';
  48359. this._scene = scene;
  48360. scene._actionManagers.push(this);
  48361. }
  48362. Object.defineProperty(ActionManager, "NothingTrigger", {
  48363. get: function () {
  48364. return ActionManager._NothingTrigger;
  48365. },
  48366. enumerable: true,
  48367. configurable: true
  48368. });
  48369. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48370. get: function () {
  48371. return ActionManager._OnPickTrigger;
  48372. },
  48373. enumerable: true,
  48374. configurable: true
  48375. });
  48376. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48377. get: function () {
  48378. return ActionManager._OnLeftPickTrigger;
  48379. },
  48380. enumerable: true,
  48381. configurable: true
  48382. });
  48383. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48384. get: function () {
  48385. return ActionManager._OnRightPickTrigger;
  48386. },
  48387. enumerable: true,
  48388. configurable: true
  48389. });
  48390. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48391. get: function () {
  48392. return ActionManager._OnCenterPickTrigger;
  48393. },
  48394. enumerable: true,
  48395. configurable: true
  48396. });
  48397. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48398. get: function () {
  48399. return ActionManager._OnPickDownTrigger;
  48400. },
  48401. enumerable: true,
  48402. configurable: true
  48403. });
  48404. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48405. get: function () {
  48406. return ActionManager._OnDoublePickTrigger;
  48407. },
  48408. enumerable: true,
  48409. configurable: true
  48410. });
  48411. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48412. get: function () {
  48413. return ActionManager._OnPickUpTrigger;
  48414. },
  48415. enumerable: true,
  48416. configurable: true
  48417. });
  48418. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48419. /// This trigger will only be raised if you also declared a OnPickDown
  48420. get: function () {
  48421. return ActionManager._OnPickOutTrigger;
  48422. },
  48423. enumerable: true,
  48424. configurable: true
  48425. });
  48426. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48427. get: function () {
  48428. return ActionManager._OnLongPressTrigger;
  48429. },
  48430. enumerable: true,
  48431. configurable: true
  48432. });
  48433. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48434. get: function () {
  48435. return ActionManager._OnPointerOverTrigger;
  48436. },
  48437. enumerable: true,
  48438. configurable: true
  48439. });
  48440. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48441. get: function () {
  48442. return ActionManager._OnPointerOutTrigger;
  48443. },
  48444. enumerable: true,
  48445. configurable: true
  48446. });
  48447. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48448. get: function () {
  48449. return ActionManager._OnEveryFrameTrigger;
  48450. },
  48451. enumerable: true,
  48452. configurable: true
  48453. });
  48454. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48455. get: function () {
  48456. return ActionManager._OnIntersectionEnterTrigger;
  48457. },
  48458. enumerable: true,
  48459. configurable: true
  48460. });
  48461. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48462. get: function () {
  48463. return ActionManager._OnIntersectionExitTrigger;
  48464. },
  48465. enumerable: true,
  48466. configurable: true
  48467. });
  48468. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48469. get: function () {
  48470. return ActionManager._OnKeyDownTrigger;
  48471. },
  48472. enumerable: true,
  48473. configurable: true
  48474. });
  48475. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48476. get: function () {
  48477. return ActionManager._OnKeyUpTrigger;
  48478. },
  48479. enumerable: true,
  48480. configurable: true
  48481. });
  48482. // Methods
  48483. ActionManager.prototype.dispose = function () {
  48484. var index = this._scene._actionManagers.indexOf(this);
  48485. for (var i = 0; i < this.actions.length; i++) {
  48486. var action = this.actions[i];
  48487. ActionManager.Triggers[action.trigger]--;
  48488. if (ActionManager.Triggers[action.trigger] === 0) {
  48489. delete ActionManager.Triggers[action.trigger];
  48490. }
  48491. }
  48492. if (index > -1) {
  48493. this._scene._actionManagers.splice(index, 1);
  48494. }
  48495. };
  48496. ActionManager.prototype.getScene = function () {
  48497. return this._scene;
  48498. };
  48499. /**
  48500. * Does this action manager handles actions of any of the given triggers
  48501. * @param {number[]} triggers - the triggers to be tested
  48502. * @return {boolean} whether one (or more) of the triggers is handeled
  48503. */
  48504. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48505. for (var index = 0; index < this.actions.length; index++) {
  48506. var action = this.actions[index];
  48507. if (triggers.indexOf(action.trigger) > -1) {
  48508. return true;
  48509. }
  48510. }
  48511. return false;
  48512. };
  48513. /**
  48514. * Does this action manager handles actions of a given trigger
  48515. * @param {number} trigger - the trigger to be tested
  48516. * @return {boolean} whether the trigger is handeled
  48517. */
  48518. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48519. for (var index = 0; index < this.actions.length; index++) {
  48520. var action = this.actions[index];
  48521. if (action.trigger === trigger) {
  48522. return true;
  48523. }
  48524. }
  48525. return false;
  48526. };
  48527. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48528. /**
  48529. * Does this action manager has pointer triggers
  48530. * @return {boolean} whether or not it has pointer triggers
  48531. */
  48532. get: function () {
  48533. for (var index = 0; index < this.actions.length; index++) {
  48534. var action = this.actions[index];
  48535. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48536. return true;
  48537. }
  48538. }
  48539. return false;
  48540. },
  48541. enumerable: true,
  48542. configurable: true
  48543. });
  48544. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48545. /**
  48546. * Does this action manager has pick triggers
  48547. * @return {boolean} whether or not it has pick triggers
  48548. */
  48549. get: function () {
  48550. for (var index = 0; index < this.actions.length; index++) {
  48551. var action = this.actions[index];
  48552. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48553. return true;
  48554. }
  48555. }
  48556. return false;
  48557. },
  48558. enumerable: true,
  48559. configurable: true
  48560. });
  48561. Object.defineProperty(ActionManager, "HasTriggers", {
  48562. /**
  48563. * Does exist one action manager with at least one trigger
  48564. * @return {boolean} whether or not it exists one action manager with one trigger
  48565. **/
  48566. get: function () {
  48567. for (var t in ActionManager.Triggers) {
  48568. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48569. return true;
  48570. }
  48571. }
  48572. return false;
  48573. },
  48574. enumerable: true,
  48575. configurable: true
  48576. });
  48577. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48578. /**
  48579. * Does exist one action manager with at least one pick trigger
  48580. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48581. **/
  48582. get: function () {
  48583. for (var t in ActionManager.Triggers) {
  48584. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48585. var t_int = parseInt(t);
  48586. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48587. return true;
  48588. }
  48589. }
  48590. }
  48591. return false;
  48592. },
  48593. enumerable: true,
  48594. configurable: true
  48595. });
  48596. /**
  48597. * Does exist one action manager that handles actions of a given trigger
  48598. * @param {number} trigger - the trigger to be tested
  48599. * @return {boolean} whether the trigger is handeled by at least one action manager
  48600. **/
  48601. ActionManager.HasSpecificTrigger = function (trigger) {
  48602. for (var t in ActionManager.Triggers) {
  48603. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48604. var t_int = parseInt(t);
  48605. if (t_int === trigger) {
  48606. return true;
  48607. }
  48608. }
  48609. }
  48610. return false;
  48611. };
  48612. /**
  48613. * Registers an action to this action manager
  48614. * @param {BABYLON.Action} action - the action to be registered
  48615. * @return {BABYLON.Action} the action amended (prepared) after registration
  48616. */
  48617. ActionManager.prototype.registerAction = function (action) {
  48618. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48619. if (this.getScene().actionManager !== this) {
  48620. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48621. return null;
  48622. }
  48623. }
  48624. this.actions.push(action);
  48625. if (ActionManager.Triggers[action.trigger]) {
  48626. ActionManager.Triggers[action.trigger]++;
  48627. }
  48628. else {
  48629. ActionManager.Triggers[action.trigger] = 1;
  48630. }
  48631. action._actionManager = this;
  48632. action._prepare();
  48633. return action;
  48634. };
  48635. /**
  48636. * Unregisters an action to this action manager
  48637. * @param action The action to be unregistered
  48638. * @return whether the action has been unregistered
  48639. */
  48640. ActionManager.prototype.unregisterAction = function (action) {
  48641. var index = this.actions.indexOf(action);
  48642. if (index !== -1) {
  48643. this.actions.splice(index, 1);
  48644. ActionManager.Triggers[action.trigger] -= 1;
  48645. if (ActionManager.Triggers[action.trigger] === 0) {
  48646. delete ActionManager.Triggers[action.trigger];
  48647. }
  48648. delete action._actionManager;
  48649. return true;
  48650. }
  48651. return false;
  48652. };
  48653. /**
  48654. * Process a specific trigger
  48655. * @param {number} trigger - the trigger to process
  48656. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48657. */
  48658. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48659. for (var index = 0; index < this.actions.length; index++) {
  48660. var action = this.actions[index];
  48661. if (action.trigger === trigger) {
  48662. if (evt) {
  48663. if (trigger === ActionManager.OnKeyUpTrigger
  48664. || trigger === ActionManager.OnKeyDownTrigger) {
  48665. var parameter = action.getTriggerParameter();
  48666. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48667. if (!parameter.toLowerCase) {
  48668. continue;
  48669. }
  48670. var lowerCase = parameter.toLowerCase();
  48671. if (lowerCase !== evt.sourceEvent.key) {
  48672. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48673. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48674. if (actualkey !== lowerCase) {
  48675. continue;
  48676. }
  48677. }
  48678. }
  48679. }
  48680. }
  48681. action._executeCurrent(evt);
  48682. }
  48683. }
  48684. };
  48685. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48686. var properties = propertyPath.split(".");
  48687. for (var index = 0; index < properties.length - 1; index++) {
  48688. target = target[properties[index]];
  48689. }
  48690. return target;
  48691. };
  48692. ActionManager.prototype._getProperty = function (propertyPath) {
  48693. var properties = propertyPath.split(".");
  48694. return properties[properties.length - 1];
  48695. };
  48696. ActionManager.prototype.serialize = function (name) {
  48697. var root = {
  48698. children: new Array(),
  48699. name: name,
  48700. type: 3,
  48701. properties: new Array() // Empty for root but required
  48702. };
  48703. for (var i = 0; i < this.actions.length; i++) {
  48704. var triggerObject = {
  48705. type: 0,
  48706. children: new Array(),
  48707. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48708. properties: new Array()
  48709. };
  48710. var triggerOptions = this.actions[i].triggerOptions;
  48711. if (triggerOptions && typeof triggerOptions !== "number") {
  48712. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48713. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48714. }
  48715. else {
  48716. var parameter = {};
  48717. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48718. if (triggerOptions.parameter.mesh) {
  48719. parameter._meshId = triggerOptions.parameter.mesh.id;
  48720. }
  48721. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48722. }
  48723. }
  48724. // Serialize child action, recursively
  48725. this.actions[i].serialize(triggerObject);
  48726. // Add serialized trigger
  48727. root.children.push(triggerObject);
  48728. }
  48729. return root;
  48730. };
  48731. ActionManager.Parse = function (parsedActions, object, scene) {
  48732. var actionManager = new ActionManager(scene);
  48733. if (object === null)
  48734. scene.actionManager = actionManager;
  48735. else
  48736. object.actionManager = actionManager;
  48737. // instanciate a new object
  48738. var instanciate = function (name, params) {
  48739. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48740. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48741. newInstance.constructor.apply(newInstance, params);
  48742. return newInstance;
  48743. };
  48744. var parseParameter = function (name, value, target, propertyPath) {
  48745. if (propertyPath === null) {
  48746. // String, boolean or float
  48747. var floatValue = parseFloat(value);
  48748. if (value === "true" || value === "false")
  48749. return value === "true";
  48750. else
  48751. return isNaN(floatValue) ? value : floatValue;
  48752. }
  48753. var effectiveTarget = propertyPath.split(".");
  48754. var values = value.split(",");
  48755. // Get effective Target
  48756. for (var i = 0; i < effectiveTarget.length; i++) {
  48757. target = target[effectiveTarget[i]];
  48758. }
  48759. // Return appropriate value with its type
  48760. if (typeof (target) === "boolean")
  48761. return values[0] === "true";
  48762. if (typeof (target) === "string")
  48763. return values[0];
  48764. // Parameters with multiple values such as Vector3 etc.
  48765. var split = new Array();
  48766. for (var i = 0; i < values.length; i++)
  48767. split.push(parseFloat(values[i]));
  48768. if (target instanceof BABYLON.Vector3)
  48769. return BABYLON.Vector3.FromArray(split);
  48770. if (target instanceof BABYLON.Vector4)
  48771. return BABYLON.Vector4.FromArray(split);
  48772. if (target instanceof BABYLON.Color3)
  48773. return BABYLON.Color3.FromArray(split);
  48774. if (target instanceof BABYLON.Color4)
  48775. return BABYLON.Color4.FromArray(split);
  48776. return parseFloat(values[0]);
  48777. };
  48778. // traverse graph per trigger
  48779. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48780. if (combineArray === void 0) { combineArray = null; }
  48781. if (parsedAction.detached)
  48782. return;
  48783. var parameters = new Array();
  48784. var target = null;
  48785. var propertyPath = null;
  48786. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48787. // Parameters
  48788. if (parsedAction.type === 2)
  48789. parameters.push(actionManager);
  48790. else
  48791. parameters.push(trigger);
  48792. if (combine) {
  48793. var actions = new Array();
  48794. for (var j = 0; j < parsedAction.combine.length; j++) {
  48795. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48796. }
  48797. parameters.push(actions);
  48798. }
  48799. else {
  48800. for (var i = 0; i < parsedAction.properties.length; i++) {
  48801. var value = parsedAction.properties[i].value;
  48802. var name = parsedAction.properties[i].name;
  48803. var targetType = parsedAction.properties[i].targetType;
  48804. if (name === "target")
  48805. if (targetType !== null && targetType === "SceneProperties")
  48806. value = target = scene;
  48807. else
  48808. value = target = scene.getNodeByName(value);
  48809. else if (name === "parent")
  48810. value = scene.getNodeByName(value);
  48811. else if (name === "sound")
  48812. value = scene.getSoundByName(value);
  48813. else if (name !== "propertyPath") {
  48814. if (parsedAction.type === 2 && name === "operator")
  48815. value = BABYLON.ValueCondition[value];
  48816. else
  48817. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48818. }
  48819. else {
  48820. propertyPath = value;
  48821. }
  48822. parameters.push(value);
  48823. }
  48824. }
  48825. if (combineArray === null) {
  48826. parameters.push(condition);
  48827. }
  48828. else {
  48829. parameters.push(null);
  48830. }
  48831. // If interpolate value action
  48832. if (parsedAction.name === "InterpolateValueAction") {
  48833. var param = parameters[parameters.length - 2];
  48834. parameters[parameters.length - 1] = param;
  48835. parameters[parameters.length - 2] = condition;
  48836. }
  48837. // Action or condition(s) and not CombineAction
  48838. var newAction = instanciate(parsedAction.name, parameters);
  48839. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48840. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48841. if (action)
  48842. action.then(nothing);
  48843. else
  48844. actionManager.registerAction(nothing);
  48845. action = nothing;
  48846. }
  48847. if (combineArray === null) {
  48848. if (newAction instanceof BABYLON.Condition) {
  48849. condition = newAction;
  48850. newAction = action;
  48851. }
  48852. else {
  48853. condition = null;
  48854. if (action)
  48855. action.then(newAction);
  48856. else
  48857. actionManager.registerAction(newAction);
  48858. }
  48859. }
  48860. else {
  48861. combineArray.push(newAction);
  48862. }
  48863. for (var i = 0; i < parsedAction.children.length; i++)
  48864. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48865. };
  48866. // triggers
  48867. for (var i = 0; i < parsedActions.children.length; i++) {
  48868. var triggerParams;
  48869. var trigger = parsedActions.children[i];
  48870. if (trigger.properties.length > 0) {
  48871. var param = trigger.properties[0].value;
  48872. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48873. if (value._meshId) {
  48874. value.mesh = scene.getMeshByID(value._meshId);
  48875. }
  48876. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48877. }
  48878. else
  48879. triggerParams = ActionManager[trigger.name];
  48880. for (var j = 0; j < trigger.children.length; j++) {
  48881. if (!trigger.detached)
  48882. traverse(trigger.children[j], triggerParams, null, null);
  48883. }
  48884. }
  48885. };
  48886. ActionManager.GetTriggerName = function (trigger) {
  48887. switch (trigger) {
  48888. case 0: return "NothingTrigger";
  48889. case 1: return "OnPickTrigger";
  48890. case 2: return "OnLeftPickTrigger";
  48891. case 3: return "OnRightPickTrigger";
  48892. case 4: return "OnCenterPickTrigger";
  48893. case 5: return "OnPickDownTrigger";
  48894. case 6: return "OnPickUpTrigger";
  48895. case 7: return "OnLongPressTrigger";
  48896. case 8: return "OnPointerOverTrigger";
  48897. case 9: return "OnPointerOutTrigger";
  48898. case 10: return "OnEveryFrameTrigger";
  48899. case 11: return "OnIntersectionEnterTrigger";
  48900. case 12: return "OnIntersectionExitTrigger";
  48901. case 13: return "OnKeyDownTrigger";
  48902. case 14: return "OnKeyUpTrigger";
  48903. case 15: return "OnPickOutTrigger";
  48904. default: return "";
  48905. }
  48906. };
  48907. // Statics
  48908. ActionManager._NothingTrigger = 0;
  48909. ActionManager._OnPickTrigger = 1;
  48910. ActionManager._OnLeftPickTrigger = 2;
  48911. ActionManager._OnRightPickTrigger = 3;
  48912. ActionManager._OnCenterPickTrigger = 4;
  48913. ActionManager._OnPickDownTrigger = 5;
  48914. ActionManager._OnDoublePickTrigger = 6;
  48915. ActionManager._OnPickUpTrigger = 7;
  48916. ActionManager._OnLongPressTrigger = 8;
  48917. ActionManager._OnPointerOverTrigger = 9;
  48918. ActionManager._OnPointerOutTrigger = 10;
  48919. ActionManager._OnEveryFrameTrigger = 11;
  48920. ActionManager._OnIntersectionEnterTrigger = 12;
  48921. ActionManager._OnIntersectionExitTrigger = 13;
  48922. ActionManager._OnKeyDownTrigger = 14;
  48923. ActionManager._OnKeyUpTrigger = 15;
  48924. ActionManager._OnPickOutTrigger = 16;
  48925. ActionManager.Triggers = {};
  48926. return ActionManager;
  48927. }());
  48928. BABYLON.ActionManager = ActionManager;
  48929. })(BABYLON || (BABYLON = {}));
  48930. //# sourceMappingURL=babylon.actionManager.js.map
  48931. var BABYLON;
  48932. (function (BABYLON) {
  48933. var InterpolateValueAction = /** @class */ (function (_super) {
  48934. __extends(InterpolateValueAction, _super);
  48935. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48936. if (duration === void 0) { duration = 1000; }
  48937. var _this = _super.call(this, triggerOptions, condition) || this;
  48938. _this.propertyPath = propertyPath;
  48939. _this.value = value;
  48940. _this.duration = duration;
  48941. _this.stopOtherAnimations = stopOtherAnimations;
  48942. _this.onInterpolationDone = onInterpolationDone;
  48943. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48944. _this._target = _this._effectiveTarget = target;
  48945. return _this;
  48946. }
  48947. InterpolateValueAction.prototype._prepare = function () {
  48948. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48949. this._property = this._getProperty(this.propertyPath);
  48950. };
  48951. InterpolateValueAction.prototype.execute = function () {
  48952. var _this = this;
  48953. var scene = this._actionManager.getScene();
  48954. var keys = [
  48955. {
  48956. frame: 0,
  48957. value: this._effectiveTarget[this._property]
  48958. }, {
  48959. frame: 100,
  48960. value: this.value
  48961. }
  48962. ];
  48963. var dataType;
  48964. if (typeof this.value === "number") {
  48965. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48966. }
  48967. else if (this.value instanceof BABYLON.Color3) {
  48968. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48969. }
  48970. else if (this.value instanceof BABYLON.Vector3) {
  48971. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48972. }
  48973. else if (this.value instanceof BABYLON.Matrix) {
  48974. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48975. }
  48976. else if (this.value instanceof BABYLON.Quaternion) {
  48977. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48978. }
  48979. else {
  48980. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48981. return;
  48982. }
  48983. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48984. animation.setKeys(keys);
  48985. if (this.stopOtherAnimations) {
  48986. scene.stopAnimation(this._effectiveTarget);
  48987. }
  48988. var wrapper = function () {
  48989. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48990. if (_this.onInterpolationDone) {
  48991. _this.onInterpolationDone();
  48992. }
  48993. };
  48994. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48995. };
  48996. InterpolateValueAction.prototype.serialize = function (parent) {
  48997. return _super.prototype._serialize.call(this, {
  48998. name: "InterpolateValueAction",
  48999. properties: [
  49000. BABYLON.Action._GetTargetProperty(this._target),
  49001. { name: "propertyPath", value: this.propertyPath },
  49002. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49003. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49004. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49005. ]
  49006. }, parent);
  49007. };
  49008. return InterpolateValueAction;
  49009. }(BABYLON.Action));
  49010. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49011. })(BABYLON || (BABYLON = {}));
  49012. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49013. var BABYLON;
  49014. (function (BABYLON) {
  49015. var SwitchBooleanAction = /** @class */ (function (_super) {
  49016. __extends(SwitchBooleanAction, _super);
  49017. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49018. var _this = _super.call(this, triggerOptions, condition) || this;
  49019. _this.propertyPath = propertyPath;
  49020. _this._target = _this._effectiveTarget = target;
  49021. return _this;
  49022. }
  49023. SwitchBooleanAction.prototype._prepare = function () {
  49024. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49025. this._property = this._getProperty(this.propertyPath);
  49026. };
  49027. SwitchBooleanAction.prototype.execute = function () {
  49028. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49029. };
  49030. SwitchBooleanAction.prototype.serialize = function (parent) {
  49031. return _super.prototype._serialize.call(this, {
  49032. name: "SwitchBooleanAction",
  49033. properties: [
  49034. BABYLON.Action._GetTargetProperty(this._target),
  49035. { name: "propertyPath", value: this.propertyPath }
  49036. ]
  49037. }, parent);
  49038. };
  49039. return SwitchBooleanAction;
  49040. }(BABYLON.Action));
  49041. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49042. var SetStateAction = /** @class */ (function (_super) {
  49043. __extends(SetStateAction, _super);
  49044. function SetStateAction(triggerOptions, target, value, condition) {
  49045. var _this = _super.call(this, triggerOptions, condition) || this;
  49046. _this.value = value;
  49047. _this._target = target;
  49048. return _this;
  49049. }
  49050. SetStateAction.prototype.execute = function () {
  49051. this._target.state = this.value;
  49052. };
  49053. SetStateAction.prototype.serialize = function (parent) {
  49054. return _super.prototype._serialize.call(this, {
  49055. name: "SetStateAction",
  49056. properties: [
  49057. BABYLON.Action._GetTargetProperty(this._target),
  49058. { name: "value", value: this.value }
  49059. ]
  49060. }, parent);
  49061. };
  49062. return SetStateAction;
  49063. }(BABYLON.Action));
  49064. BABYLON.SetStateAction = SetStateAction;
  49065. var SetValueAction = /** @class */ (function (_super) {
  49066. __extends(SetValueAction, _super);
  49067. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49068. var _this = _super.call(this, triggerOptions, condition) || this;
  49069. _this.propertyPath = propertyPath;
  49070. _this.value = value;
  49071. _this._target = _this._effectiveTarget = target;
  49072. return _this;
  49073. }
  49074. SetValueAction.prototype._prepare = function () {
  49075. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49076. this._property = this._getProperty(this.propertyPath);
  49077. };
  49078. SetValueAction.prototype.execute = function () {
  49079. this._effectiveTarget[this._property] = this.value;
  49080. if (this._target.markAsDirty) {
  49081. this._target.markAsDirty(this._property);
  49082. }
  49083. };
  49084. SetValueAction.prototype.serialize = function (parent) {
  49085. return _super.prototype._serialize.call(this, {
  49086. name: "SetValueAction",
  49087. properties: [
  49088. BABYLON.Action._GetTargetProperty(this._target),
  49089. { name: "propertyPath", value: this.propertyPath },
  49090. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49091. ]
  49092. }, parent);
  49093. };
  49094. return SetValueAction;
  49095. }(BABYLON.Action));
  49096. BABYLON.SetValueAction = SetValueAction;
  49097. var IncrementValueAction = /** @class */ (function (_super) {
  49098. __extends(IncrementValueAction, _super);
  49099. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49100. var _this = _super.call(this, triggerOptions, condition) || this;
  49101. _this.propertyPath = propertyPath;
  49102. _this.value = value;
  49103. _this._target = _this._effectiveTarget = target;
  49104. return _this;
  49105. }
  49106. IncrementValueAction.prototype._prepare = function () {
  49107. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49108. this._property = this._getProperty(this.propertyPath);
  49109. if (typeof this._effectiveTarget[this._property] !== "number") {
  49110. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49111. }
  49112. };
  49113. IncrementValueAction.prototype.execute = function () {
  49114. this._effectiveTarget[this._property] += this.value;
  49115. if (this._target.markAsDirty) {
  49116. this._target.markAsDirty(this._property);
  49117. }
  49118. };
  49119. IncrementValueAction.prototype.serialize = function (parent) {
  49120. return _super.prototype._serialize.call(this, {
  49121. name: "IncrementValueAction",
  49122. properties: [
  49123. BABYLON.Action._GetTargetProperty(this._target),
  49124. { name: "propertyPath", value: this.propertyPath },
  49125. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49126. ]
  49127. }, parent);
  49128. };
  49129. return IncrementValueAction;
  49130. }(BABYLON.Action));
  49131. BABYLON.IncrementValueAction = IncrementValueAction;
  49132. var PlayAnimationAction = /** @class */ (function (_super) {
  49133. __extends(PlayAnimationAction, _super);
  49134. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49135. var _this = _super.call(this, triggerOptions, condition) || this;
  49136. _this.from = from;
  49137. _this.to = to;
  49138. _this.loop = loop;
  49139. _this._target = target;
  49140. return _this;
  49141. }
  49142. PlayAnimationAction.prototype._prepare = function () {
  49143. };
  49144. PlayAnimationAction.prototype.execute = function () {
  49145. var scene = this._actionManager.getScene();
  49146. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49147. };
  49148. PlayAnimationAction.prototype.serialize = function (parent) {
  49149. return _super.prototype._serialize.call(this, {
  49150. name: "PlayAnimationAction",
  49151. properties: [
  49152. BABYLON.Action._GetTargetProperty(this._target),
  49153. { name: "from", value: String(this.from) },
  49154. { name: "to", value: String(this.to) },
  49155. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49156. ]
  49157. }, parent);
  49158. };
  49159. return PlayAnimationAction;
  49160. }(BABYLON.Action));
  49161. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49162. var StopAnimationAction = /** @class */ (function (_super) {
  49163. __extends(StopAnimationAction, _super);
  49164. function StopAnimationAction(triggerOptions, target, condition) {
  49165. var _this = _super.call(this, triggerOptions, condition) || this;
  49166. _this._target = target;
  49167. return _this;
  49168. }
  49169. StopAnimationAction.prototype._prepare = function () {
  49170. };
  49171. StopAnimationAction.prototype.execute = function () {
  49172. var scene = this._actionManager.getScene();
  49173. scene.stopAnimation(this._target);
  49174. };
  49175. StopAnimationAction.prototype.serialize = function (parent) {
  49176. return _super.prototype._serialize.call(this, {
  49177. name: "StopAnimationAction",
  49178. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49179. }, parent);
  49180. };
  49181. return StopAnimationAction;
  49182. }(BABYLON.Action));
  49183. BABYLON.StopAnimationAction = StopAnimationAction;
  49184. var DoNothingAction = /** @class */ (function (_super) {
  49185. __extends(DoNothingAction, _super);
  49186. function DoNothingAction(triggerOptions, condition) {
  49187. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49188. return _super.call(this, triggerOptions, condition) || this;
  49189. }
  49190. DoNothingAction.prototype.execute = function () {
  49191. };
  49192. DoNothingAction.prototype.serialize = function (parent) {
  49193. return _super.prototype._serialize.call(this, {
  49194. name: "DoNothingAction",
  49195. properties: []
  49196. }, parent);
  49197. };
  49198. return DoNothingAction;
  49199. }(BABYLON.Action));
  49200. BABYLON.DoNothingAction = DoNothingAction;
  49201. var CombineAction = /** @class */ (function (_super) {
  49202. __extends(CombineAction, _super);
  49203. function CombineAction(triggerOptions, children, condition) {
  49204. var _this = _super.call(this, triggerOptions, condition) || this;
  49205. _this.children = children;
  49206. return _this;
  49207. }
  49208. CombineAction.prototype._prepare = function () {
  49209. for (var index = 0; index < this.children.length; index++) {
  49210. this.children[index]._actionManager = this._actionManager;
  49211. this.children[index]._prepare();
  49212. }
  49213. };
  49214. CombineAction.prototype.execute = function (evt) {
  49215. for (var index = 0; index < this.children.length; index++) {
  49216. this.children[index].execute(evt);
  49217. }
  49218. };
  49219. CombineAction.prototype.serialize = function (parent) {
  49220. var serializationObject = _super.prototype._serialize.call(this, {
  49221. name: "CombineAction",
  49222. properties: [],
  49223. combine: []
  49224. }, parent);
  49225. for (var i = 0; i < this.children.length; i++) {
  49226. serializationObject.combine.push(this.children[i].serialize(null));
  49227. }
  49228. return serializationObject;
  49229. };
  49230. return CombineAction;
  49231. }(BABYLON.Action));
  49232. BABYLON.CombineAction = CombineAction;
  49233. var ExecuteCodeAction = /** @class */ (function (_super) {
  49234. __extends(ExecuteCodeAction, _super);
  49235. function ExecuteCodeAction(triggerOptions, func, condition) {
  49236. var _this = _super.call(this, triggerOptions, condition) || this;
  49237. _this.func = func;
  49238. return _this;
  49239. }
  49240. ExecuteCodeAction.prototype.execute = function (evt) {
  49241. this.func(evt);
  49242. };
  49243. return ExecuteCodeAction;
  49244. }(BABYLON.Action));
  49245. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49246. var SetParentAction = /** @class */ (function (_super) {
  49247. __extends(SetParentAction, _super);
  49248. function SetParentAction(triggerOptions, target, parent, condition) {
  49249. var _this = _super.call(this, triggerOptions, condition) || this;
  49250. _this._target = target;
  49251. _this._parent = parent;
  49252. return _this;
  49253. }
  49254. SetParentAction.prototype._prepare = function () {
  49255. };
  49256. SetParentAction.prototype.execute = function () {
  49257. if (this._target.parent === this._parent) {
  49258. return;
  49259. }
  49260. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49261. invertParentWorldMatrix.invert();
  49262. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49263. this._target.parent = this._parent;
  49264. };
  49265. SetParentAction.prototype.serialize = function (parent) {
  49266. return _super.prototype._serialize.call(this, {
  49267. name: "SetParentAction",
  49268. properties: [
  49269. BABYLON.Action._GetTargetProperty(this._target),
  49270. BABYLON.Action._GetTargetProperty(this._parent),
  49271. ]
  49272. }, parent);
  49273. };
  49274. return SetParentAction;
  49275. }(BABYLON.Action));
  49276. BABYLON.SetParentAction = SetParentAction;
  49277. var PlaySoundAction = /** @class */ (function (_super) {
  49278. __extends(PlaySoundAction, _super);
  49279. function PlaySoundAction(triggerOptions, sound, condition) {
  49280. var _this = _super.call(this, triggerOptions, condition) || this;
  49281. _this._sound = sound;
  49282. return _this;
  49283. }
  49284. PlaySoundAction.prototype._prepare = function () {
  49285. };
  49286. PlaySoundAction.prototype.execute = function () {
  49287. if (this._sound !== undefined)
  49288. this._sound.play();
  49289. };
  49290. PlaySoundAction.prototype.serialize = function (parent) {
  49291. return _super.prototype._serialize.call(this, {
  49292. name: "PlaySoundAction",
  49293. properties: [{ name: "sound", value: this._sound.name }]
  49294. }, parent);
  49295. };
  49296. return PlaySoundAction;
  49297. }(BABYLON.Action));
  49298. BABYLON.PlaySoundAction = PlaySoundAction;
  49299. var StopSoundAction = /** @class */ (function (_super) {
  49300. __extends(StopSoundAction, _super);
  49301. function StopSoundAction(triggerOptions, sound, condition) {
  49302. var _this = _super.call(this, triggerOptions, condition) || this;
  49303. _this._sound = sound;
  49304. return _this;
  49305. }
  49306. StopSoundAction.prototype._prepare = function () {
  49307. };
  49308. StopSoundAction.prototype.execute = function () {
  49309. if (this._sound !== undefined)
  49310. this._sound.stop();
  49311. };
  49312. StopSoundAction.prototype.serialize = function (parent) {
  49313. return _super.prototype._serialize.call(this, {
  49314. name: "StopSoundAction",
  49315. properties: [{ name: "sound", value: this._sound.name }]
  49316. }, parent);
  49317. };
  49318. return StopSoundAction;
  49319. }(BABYLON.Action));
  49320. BABYLON.StopSoundAction = StopSoundAction;
  49321. })(BABYLON || (BABYLON = {}));
  49322. //# sourceMappingURL=babylon.directActions.js.map
  49323. var BABYLON;
  49324. (function (BABYLON) {
  49325. var SpriteManager = /** @class */ (function () {
  49326. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49327. if (epsilon === void 0) { epsilon = 0.01; }
  49328. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49329. this.name = name;
  49330. this.sprites = new Array();
  49331. this.renderingGroupId = 0;
  49332. this.layerMask = 0x0FFFFFFF;
  49333. this.fogEnabled = true;
  49334. this.isPickable = false;
  49335. /**
  49336. * An event triggered when the manager is disposed.
  49337. * @type {BABYLON.Observable}
  49338. */
  49339. this.onDisposeObservable = new BABYLON.Observable();
  49340. this._vertexBuffers = {};
  49341. this._capacity = capacity;
  49342. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49343. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49344. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49345. if (cellSize.width && cellSize.height) {
  49346. this.cellWidth = cellSize.width;
  49347. this.cellHeight = cellSize.height;
  49348. }
  49349. else if (cellSize !== undefined) {
  49350. this.cellWidth = cellSize;
  49351. this.cellHeight = cellSize;
  49352. }
  49353. else {
  49354. return;
  49355. }
  49356. this._epsilon = epsilon;
  49357. this._scene = scene;
  49358. this._scene.spriteManagers.push(this);
  49359. var indices = [];
  49360. var index = 0;
  49361. for (var count = 0; count < capacity; count++) {
  49362. indices.push(index);
  49363. indices.push(index + 1);
  49364. indices.push(index + 2);
  49365. indices.push(index);
  49366. indices.push(index + 2);
  49367. indices.push(index + 3);
  49368. index += 4;
  49369. }
  49370. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49371. // VBO
  49372. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49373. this._vertexData = new Float32Array(capacity * 16 * 4);
  49374. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49375. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49376. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49377. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49378. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49379. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49380. this._vertexBuffers["options"] = options;
  49381. this._vertexBuffers["cellInfo"] = cellInfo;
  49382. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49383. // Effects
  49384. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49385. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49386. }
  49387. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49388. set: function (callback) {
  49389. if (this._onDisposeObserver) {
  49390. this.onDisposeObservable.remove(this._onDisposeObserver);
  49391. }
  49392. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49393. },
  49394. enumerable: true,
  49395. configurable: true
  49396. });
  49397. Object.defineProperty(SpriteManager.prototype, "texture", {
  49398. get: function () {
  49399. return this._spriteTexture;
  49400. },
  49401. set: function (value) {
  49402. this._spriteTexture = value;
  49403. },
  49404. enumerable: true,
  49405. configurable: true
  49406. });
  49407. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49408. var arrayOffset = index * 16;
  49409. if (offsetX === 0)
  49410. offsetX = this._epsilon;
  49411. else if (offsetX === 1)
  49412. offsetX = 1 - this._epsilon;
  49413. if (offsetY === 0)
  49414. offsetY = this._epsilon;
  49415. else if (offsetY === 1)
  49416. offsetY = 1 - this._epsilon;
  49417. this._vertexData[arrayOffset] = sprite.position.x;
  49418. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49419. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49420. this._vertexData[arrayOffset + 3] = sprite.angle;
  49421. this._vertexData[arrayOffset + 4] = sprite.width;
  49422. this._vertexData[arrayOffset + 5] = sprite.height;
  49423. this._vertexData[arrayOffset + 6] = offsetX;
  49424. this._vertexData[arrayOffset + 7] = offsetY;
  49425. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49426. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49427. var offset = (sprite.cellIndex / rowSize) >> 0;
  49428. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49429. this._vertexData[arrayOffset + 11] = offset;
  49430. // Color
  49431. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49432. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49433. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49434. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49435. };
  49436. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49437. var count = Math.min(this._capacity, this.sprites.length);
  49438. var min = BABYLON.Vector3.Zero();
  49439. var max = BABYLON.Vector3.Zero();
  49440. var distance = Number.MAX_VALUE;
  49441. var currentSprite = null;
  49442. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49443. var cameraView = camera.getViewMatrix();
  49444. for (var index = 0; index < count; index++) {
  49445. var sprite = this.sprites[index];
  49446. if (!sprite) {
  49447. continue;
  49448. }
  49449. if (predicate) {
  49450. if (!predicate(sprite)) {
  49451. continue;
  49452. }
  49453. }
  49454. else if (!sprite.isPickable) {
  49455. continue;
  49456. }
  49457. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49458. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49459. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49460. if (ray.intersectsBoxMinMax(min, max)) {
  49461. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49462. if (distance > currentDistance) {
  49463. distance = currentDistance;
  49464. currentSprite = sprite;
  49465. if (fastCheck) {
  49466. break;
  49467. }
  49468. }
  49469. }
  49470. }
  49471. if (currentSprite) {
  49472. var result = new BABYLON.PickingInfo();
  49473. result.hit = true;
  49474. result.pickedSprite = currentSprite;
  49475. result.distance = distance;
  49476. return result;
  49477. }
  49478. return null;
  49479. };
  49480. SpriteManager.prototype.render = function () {
  49481. // Check
  49482. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49483. return;
  49484. var engine = this._scene.getEngine();
  49485. var baseSize = this._spriteTexture.getBaseSize();
  49486. // Sprites
  49487. var deltaTime = engine.getDeltaTime();
  49488. var max = Math.min(this._capacity, this.sprites.length);
  49489. var rowSize = baseSize.width / this.cellWidth;
  49490. var offset = 0;
  49491. for (var index = 0; index < max; index++) {
  49492. var sprite = this.sprites[index];
  49493. if (!sprite) {
  49494. continue;
  49495. }
  49496. sprite._animate(deltaTime);
  49497. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49498. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49499. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49500. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49501. }
  49502. this._buffer.update(this._vertexData);
  49503. // Render
  49504. var effect = this._effectBase;
  49505. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49506. effect = this._effectFog;
  49507. }
  49508. engine.enableEffect(effect);
  49509. var viewMatrix = this._scene.getViewMatrix();
  49510. effect.setTexture("diffuseSampler", this._spriteTexture);
  49511. effect.setMatrix("view", viewMatrix);
  49512. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49513. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49514. // Fog
  49515. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49516. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49517. effect.setColor3("vFogColor", this._scene.fogColor);
  49518. }
  49519. // VBOs
  49520. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49521. // Draw order
  49522. engine.setDepthFunctionToLessOrEqual();
  49523. effect.setBool("alphaTest", true);
  49524. engine.setColorWrite(false);
  49525. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49526. engine.setColorWrite(true);
  49527. effect.setBool("alphaTest", false);
  49528. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49529. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49530. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49531. };
  49532. SpriteManager.prototype.dispose = function () {
  49533. if (this._buffer) {
  49534. this._buffer.dispose();
  49535. this._buffer = null;
  49536. }
  49537. if (this._indexBuffer) {
  49538. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49539. this._indexBuffer = null;
  49540. }
  49541. if (this._spriteTexture) {
  49542. this._spriteTexture.dispose();
  49543. this._spriteTexture = null;
  49544. }
  49545. // Remove from scene
  49546. var index = this._scene.spriteManagers.indexOf(this);
  49547. this._scene.spriteManagers.splice(index, 1);
  49548. // Callback
  49549. this.onDisposeObservable.notifyObservers(this);
  49550. this.onDisposeObservable.clear();
  49551. };
  49552. return SpriteManager;
  49553. }());
  49554. BABYLON.SpriteManager = SpriteManager;
  49555. })(BABYLON || (BABYLON = {}));
  49556. //# sourceMappingURL=babylon.spriteManager.js.map
  49557. var BABYLON;
  49558. (function (BABYLON) {
  49559. var Sprite = /** @class */ (function () {
  49560. function Sprite(name, manager) {
  49561. this.name = name;
  49562. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49563. this.width = 1.0;
  49564. this.height = 1.0;
  49565. this.angle = 0;
  49566. this.cellIndex = 0;
  49567. this.invertU = 0;
  49568. this.invertV = 0;
  49569. this.animations = new Array();
  49570. this.isPickable = false;
  49571. this._animationStarted = false;
  49572. this._loopAnimation = false;
  49573. this._fromIndex = 0;
  49574. this._toIndex = 0;
  49575. this._delay = 0;
  49576. this._direction = 1;
  49577. this._time = 0;
  49578. this._manager = manager;
  49579. this._manager.sprites.push(this);
  49580. this.position = BABYLON.Vector3.Zero();
  49581. }
  49582. Object.defineProperty(Sprite.prototype, "size", {
  49583. get: function () {
  49584. return this.width;
  49585. },
  49586. set: function (value) {
  49587. this.width = value;
  49588. this.height = value;
  49589. },
  49590. enumerable: true,
  49591. configurable: true
  49592. });
  49593. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49594. this._fromIndex = from;
  49595. this._toIndex = to;
  49596. this._loopAnimation = loop;
  49597. this._delay = delay;
  49598. this._animationStarted = true;
  49599. this._direction = from < to ? 1 : -1;
  49600. this.cellIndex = from;
  49601. this._time = 0;
  49602. this._onAnimationEnd = onAnimationEnd;
  49603. };
  49604. Sprite.prototype.stopAnimation = function () {
  49605. this._animationStarted = false;
  49606. };
  49607. Sprite.prototype._animate = function (deltaTime) {
  49608. if (!this._animationStarted)
  49609. return;
  49610. this._time += deltaTime;
  49611. if (this._time > this._delay) {
  49612. this._time = this._time % this._delay;
  49613. this.cellIndex += this._direction;
  49614. if (this.cellIndex > this._toIndex) {
  49615. if (this._loopAnimation) {
  49616. this.cellIndex = this._fromIndex;
  49617. }
  49618. else {
  49619. this.cellIndex = this._toIndex;
  49620. this._animationStarted = false;
  49621. if (this._onAnimationEnd) {
  49622. this._onAnimationEnd();
  49623. }
  49624. if (this.disposeWhenFinishedAnimating) {
  49625. this.dispose();
  49626. }
  49627. }
  49628. }
  49629. }
  49630. };
  49631. Sprite.prototype.dispose = function () {
  49632. for (var i = 0; i < this._manager.sprites.length; i++) {
  49633. if (this._manager.sprites[i] == this) {
  49634. this._manager.sprites.splice(i, 1);
  49635. }
  49636. }
  49637. };
  49638. return Sprite;
  49639. }());
  49640. BABYLON.Sprite = Sprite;
  49641. })(BABYLON || (BABYLON = {}));
  49642. //# sourceMappingURL=babylon.sprite.js.map
  49643. var BABYLON;
  49644. (function (BABYLON) {
  49645. var IntersectionInfo = /** @class */ (function () {
  49646. function IntersectionInfo(bu, bv, distance) {
  49647. this.bu = bu;
  49648. this.bv = bv;
  49649. this.distance = distance;
  49650. this.faceId = 0;
  49651. this.subMeshId = 0;
  49652. }
  49653. return IntersectionInfo;
  49654. }());
  49655. BABYLON.IntersectionInfo = IntersectionInfo;
  49656. var PickingInfo = /** @class */ (function () {
  49657. function PickingInfo() {
  49658. this.hit = false;
  49659. this.distance = 0;
  49660. this.pickedPoint = null;
  49661. this.pickedMesh = null;
  49662. this.bu = 0;
  49663. this.bv = 0;
  49664. this.faceId = -1;
  49665. this.subMeshId = 0;
  49666. this.pickedSprite = null;
  49667. }
  49668. // Methods
  49669. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49670. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49671. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49672. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49673. return null;
  49674. }
  49675. var indices = this.pickedMesh.getIndices();
  49676. if (!indices) {
  49677. return null;
  49678. }
  49679. var result;
  49680. if (useVerticesNormals) {
  49681. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49682. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49683. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49684. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49685. normal0 = normal0.scale(this.bu);
  49686. normal1 = normal1.scale(this.bv);
  49687. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49688. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49689. }
  49690. else {
  49691. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49692. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49693. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49694. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49695. var p1p2 = vertex1.subtract(vertex2);
  49696. var p3p2 = vertex3.subtract(vertex2);
  49697. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49698. }
  49699. if (useWorldCoordinates) {
  49700. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49701. }
  49702. return BABYLON.Vector3.Normalize(result);
  49703. };
  49704. PickingInfo.prototype.getTextureCoordinates = function () {
  49705. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49706. return null;
  49707. }
  49708. var indices = this.pickedMesh.getIndices();
  49709. if (!indices) {
  49710. return null;
  49711. }
  49712. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49713. if (!uvs) {
  49714. return null;
  49715. }
  49716. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49717. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49718. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49719. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49720. uv1 = uv1.scale(this.bu);
  49721. uv2 = uv2.scale(this.bv);
  49722. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49723. };
  49724. return PickingInfo;
  49725. }());
  49726. BABYLON.PickingInfo = PickingInfo;
  49727. })(BABYLON || (BABYLON = {}));
  49728. //# sourceMappingURL=babylon.pickingInfo.js.map
  49729. var BABYLON;
  49730. (function (BABYLON) {
  49731. var Ray = /** @class */ (function () {
  49732. function Ray(origin, direction, length) {
  49733. if (length === void 0) { length = Number.MAX_VALUE; }
  49734. this.origin = origin;
  49735. this.direction = direction;
  49736. this.length = length;
  49737. }
  49738. // Methods
  49739. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49740. var d = 0.0;
  49741. var maxValue = Number.MAX_VALUE;
  49742. var inv;
  49743. var min;
  49744. var max;
  49745. var temp;
  49746. if (Math.abs(this.direction.x) < 0.0000001) {
  49747. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49748. return false;
  49749. }
  49750. }
  49751. else {
  49752. inv = 1.0 / this.direction.x;
  49753. min = (minimum.x - this.origin.x) * inv;
  49754. max = (maximum.x - this.origin.x) * inv;
  49755. if (max === -Infinity) {
  49756. max = Infinity;
  49757. }
  49758. if (min > max) {
  49759. temp = min;
  49760. min = max;
  49761. max = temp;
  49762. }
  49763. d = Math.max(min, d);
  49764. maxValue = Math.min(max, maxValue);
  49765. if (d > maxValue) {
  49766. return false;
  49767. }
  49768. }
  49769. if (Math.abs(this.direction.y) < 0.0000001) {
  49770. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49771. return false;
  49772. }
  49773. }
  49774. else {
  49775. inv = 1.0 / this.direction.y;
  49776. min = (minimum.y - this.origin.y) * inv;
  49777. max = (maximum.y - this.origin.y) * inv;
  49778. if (max === -Infinity) {
  49779. max = Infinity;
  49780. }
  49781. if (min > max) {
  49782. temp = min;
  49783. min = max;
  49784. max = temp;
  49785. }
  49786. d = Math.max(min, d);
  49787. maxValue = Math.min(max, maxValue);
  49788. if (d > maxValue) {
  49789. return false;
  49790. }
  49791. }
  49792. if (Math.abs(this.direction.z) < 0.0000001) {
  49793. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49794. return false;
  49795. }
  49796. }
  49797. else {
  49798. inv = 1.0 / this.direction.z;
  49799. min = (minimum.z - this.origin.z) * inv;
  49800. max = (maximum.z - this.origin.z) * inv;
  49801. if (max === -Infinity) {
  49802. max = Infinity;
  49803. }
  49804. if (min > max) {
  49805. temp = min;
  49806. min = max;
  49807. max = temp;
  49808. }
  49809. d = Math.max(min, d);
  49810. maxValue = Math.min(max, maxValue);
  49811. if (d > maxValue) {
  49812. return false;
  49813. }
  49814. }
  49815. return true;
  49816. };
  49817. Ray.prototype.intersectsBox = function (box) {
  49818. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49819. };
  49820. Ray.prototype.intersectsSphere = function (sphere) {
  49821. var x = sphere.center.x - this.origin.x;
  49822. var y = sphere.center.y - this.origin.y;
  49823. var z = sphere.center.z - this.origin.z;
  49824. var pyth = (x * x) + (y * y) + (z * z);
  49825. var rr = sphere.radius * sphere.radius;
  49826. if (pyth <= rr) {
  49827. return true;
  49828. }
  49829. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49830. if (dot < 0.0) {
  49831. return false;
  49832. }
  49833. var temp = pyth - (dot * dot);
  49834. return temp <= rr;
  49835. };
  49836. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49837. if (!this._edge1) {
  49838. this._edge1 = BABYLON.Vector3.Zero();
  49839. this._edge2 = BABYLON.Vector3.Zero();
  49840. this._pvec = BABYLON.Vector3.Zero();
  49841. this._tvec = BABYLON.Vector3.Zero();
  49842. this._qvec = BABYLON.Vector3.Zero();
  49843. }
  49844. vertex1.subtractToRef(vertex0, this._edge1);
  49845. vertex2.subtractToRef(vertex0, this._edge2);
  49846. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49847. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49848. if (det === 0) {
  49849. return null;
  49850. }
  49851. var invdet = 1 / det;
  49852. this.origin.subtractToRef(vertex0, this._tvec);
  49853. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49854. if (bu < 0 || bu > 1.0) {
  49855. return null;
  49856. }
  49857. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49858. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49859. if (bv < 0 || bu + bv > 1.0) {
  49860. return null;
  49861. }
  49862. //check if the distance is longer than the predefined length.
  49863. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49864. if (distance > this.length) {
  49865. return null;
  49866. }
  49867. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49868. };
  49869. Ray.prototype.intersectsPlane = function (plane) {
  49870. var distance;
  49871. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49872. if (Math.abs(result1) < 9.99999997475243E-07) {
  49873. return null;
  49874. }
  49875. else {
  49876. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49877. distance = (-plane.d - result2) / result1;
  49878. if (distance < 0.0) {
  49879. if (distance < -9.99999997475243E-07) {
  49880. return null;
  49881. }
  49882. else {
  49883. return 0;
  49884. }
  49885. }
  49886. return distance;
  49887. }
  49888. };
  49889. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49890. var tm = BABYLON.Tmp.Matrix[0];
  49891. mesh.getWorldMatrix().invertToRef(tm);
  49892. if (this._tmpRay) {
  49893. Ray.TransformToRef(this, tm, this._tmpRay);
  49894. }
  49895. else {
  49896. this._tmpRay = Ray.Transform(this, tm);
  49897. }
  49898. return mesh.intersects(this._tmpRay, fastCheck);
  49899. };
  49900. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49901. if (results) {
  49902. results.length = 0;
  49903. }
  49904. else {
  49905. results = [];
  49906. }
  49907. for (var i = 0; i < meshes.length; i++) {
  49908. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49909. if (pickInfo.hit) {
  49910. results.push(pickInfo);
  49911. }
  49912. }
  49913. results.sort(this._comparePickingInfo);
  49914. return results;
  49915. };
  49916. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49917. if (pickingInfoA.distance < pickingInfoB.distance) {
  49918. return -1;
  49919. }
  49920. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49921. return 1;
  49922. }
  49923. else {
  49924. return 0;
  49925. }
  49926. };
  49927. /**
  49928. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49929. * @param sega the first point of the segment to test the intersection against
  49930. * @param segb the second point of the segment to test the intersection against
  49931. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49932. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49933. */
  49934. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49935. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49936. var u = segb.subtract(sega);
  49937. var v = rsegb.subtract(this.origin);
  49938. var w = sega.subtract(this.origin);
  49939. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49940. var b = BABYLON.Vector3.Dot(u, v);
  49941. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49942. var d = BABYLON.Vector3.Dot(u, w);
  49943. var e = BABYLON.Vector3.Dot(v, w);
  49944. var D = a * c - b * b; // always >= 0
  49945. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49946. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49947. // compute the line parameters of the two closest points
  49948. if (D < Ray.smallnum) {
  49949. sN = 0.0; // force using point P0 on segment S1
  49950. sD = 1.0; // to prevent possible division by 0.0 later
  49951. tN = e;
  49952. tD = c;
  49953. }
  49954. else {
  49955. sN = (b * e - c * d);
  49956. tN = (a * e - b * d);
  49957. if (sN < 0.0) {
  49958. sN = 0.0;
  49959. tN = e;
  49960. tD = c;
  49961. }
  49962. else if (sN > sD) {
  49963. sN = sD;
  49964. tN = e + b;
  49965. tD = c;
  49966. }
  49967. }
  49968. if (tN < 0.0) {
  49969. tN = 0.0;
  49970. // recompute sc for this edge
  49971. if (-d < 0.0) {
  49972. sN = 0.0;
  49973. }
  49974. else if (-d > a)
  49975. sN = sD;
  49976. else {
  49977. sN = -d;
  49978. sD = a;
  49979. }
  49980. }
  49981. else if (tN > tD) {
  49982. tN = tD;
  49983. // recompute sc for this edge
  49984. if ((-d + b) < 0.0) {
  49985. sN = 0;
  49986. }
  49987. else if ((-d + b) > a) {
  49988. sN = sD;
  49989. }
  49990. else {
  49991. sN = (-d + b);
  49992. sD = a;
  49993. }
  49994. }
  49995. // finally do the division to get sc and tc
  49996. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49997. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49998. // get the difference of the two closest points
  49999. var qtc = v.multiplyByFloats(tc, tc, tc);
  50000. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50001. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50002. if (isIntersected) {
  50003. return qtc.length();
  50004. }
  50005. return -1;
  50006. };
  50007. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50008. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50009. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50010. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50011. this.direction.normalize();
  50012. return this;
  50013. };
  50014. // Statics
  50015. Ray.Zero = function () {
  50016. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50017. };
  50018. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50019. var result = Ray.Zero();
  50020. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50021. };
  50022. /**
  50023. * 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
  50024. * transformed to the given world matrix.
  50025. * @param origin The origin point
  50026. * @param end The end point
  50027. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50028. */
  50029. Ray.CreateNewFromTo = function (origin, end, world) {
  50030. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50031. var direction = end.subtract(origin);
  50032. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50033. direction.normalize();
  50034. return Ray.Transform(new Ray(origin, direction, length), world);
  50035. };
  50036. Ray.Transform = function (ray, matrix) {
  50037. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50038. Ray.TransformToRef(ray, matrix, result);
  50039. return result;
  50040. };
  50041. Ray.TransformToRef = function (ray, matrix, result) {
  50042. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50043. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50044. result.length = ray.length;
  50045. var dir = result.direction;
  50046. var len = dir.length();
  50047. if (!(len === 0 || len === 1)) {
  50048. var num = 1.0 / len;
  50049. dir.x *= num;
  50050. dir.y *= num;
  50051. dir.z *= num;
  50052. result.length *= len;
  50053. }
  50054. };
  50055. Ray.smallnum = 0.00000001;
  50056. Ray.rayl = 10e8;
  50057. return Ray;
  50058. }());
  50059. BABYLON.Ray = Ray;
  50060. })(BABYLON || (BABYLON = {}));
  50061. //# sourceMappingURL=babylon.ray.js.map
  50062. var BABYLON;
  50063. (function (BABYLON) {
  50064. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50065. if (boxMin.x > sphereCenter.x + sphereRadius)
  50066. return false;
  50067. if (sphereCenter.x - sphereRadius > boxMax.x)
  50068. return false;
  50069. if (boxMin.y > sphereCenter.y + sphereRadius)
  50070. return false;
  50071. if (sphereCenter.y - sphereRadius > boxMax.y)
  50072. return false;
  50073. if (boxMin.z > sphereCenter.z + sphereRadius)
  50074. return false;
  50075. if (sphereCenter.z - sphereRadius > boxMax.z)
  50076. return false;
  50077. return true;
  50078. };
  50079. var getLowestRoot = (function () {
  50080. var result = { root: 0, found: false };
  50081. return function (a, b, c, maxR) {
  50082. result.root = 0;
  50083. result.found = false;
  50084. var determinant = b * b - 4.0 * a * c;
  50085. if (determinant < 0)
  50086. return result;
  50087. var sqrtD = Math.sqrt(determinant);
  50088. var r1 = (-b - sqrtD) / (2.0 * a);
  50089. var r2 = (-b + sqrtD) / (2.0 * a);
  50090. if (r1 > r2) {
  50091. var temp = r2;
  50092. r2 = r1;
  50093. r1 = temp;
  50094. }
  50095. if (r1 > 0 && r1 < maxR) {
  50096. result.root = r1;
  50097. result.found = true;
  50098. return result;
  50099. }
  50100. if (r2 > 0 && r2 < maxR) {
  50101. result.root = r2;
  50102. result.found = true;
  50103. return result;
  50104. }
  50105. return result;
  50106. };
  50107. })();
  50108. var Collider = /** @class */ (function () {
  50109. function Collider() {
  50110. this._collisionPoint = BABYLON.Vector3.Zero();
  50111. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50112. this._tempVector = BABYLON.Vector3.Zero();
  50113. this._tempVector2 = BABYLON.Vector3.Zero();
  50114. this._tempVector3 = BABYLON.Vector3.Zero();
  50115. this._tempVector4 = BABYLON.Vector3.Zero();
  50116. this._edge = BABYLON.Vector3.Zero();
  50117. this._baseToVertex = BABYLON.Vector3.Zero();
  50118. this._destinationPoint = BABYLON.Vector3.Zero();
  50119. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50120. this._displacementVector = BABYLON.Vector3.Zero();
  50121. this._radius = BABYLON.Vector3.One();
  50122. this._retry = 0;
  50123. this._basePointWorld = BABYLON.Vector3.Zero();
  50124. this._velocityWorld = BABYLON.Vector3.Zero();
  50125. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50126. this._collisionMask = -1;
  50127. }
  50128. Object.defineProperty(Collider.prototype, "collisionMask", {
  50129. get: function () {
  50130. return this._collisionMask;
  50131. },
  50132. set: function (mask) {
  50133. this._collisionMask = !isNaN(mask) ? mask : -1;
  50134. },
  50135. enumerable: true,
  50136. configurable: true
  50137. });
  50138. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50139. /**
  50140. * Gets the plane normal used to compute the sliding response (in local space)
  50141. */
  50142. get: function () {
  50143. return this._slidePlaneNormal;
  50144. },
  50145. enumerable: true,
  50146. configurable: true
  50147. });
  50148. // Methods
  50149. Collider.prototype._initialize = function (source, dir, e) {
  50150. this._velocity = dir;
  50151. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50152. this._basePoint = source;
  50153. source.multiplyToRef(this._radius, this._basePointWorld);
  50154. dir.multiplyToRef(this._radius, this._velocityWorld);
  50155. this._velocityWorldLength = this._velocityWorld.length();
  50156. this._epsilon = e;
  50157. this.collisionFound = false;
  50158. };
  50159. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50160. pa.subtractToRef(point, this._tempVector);
  50161. pb.subtractToRef(point, this._tempVector2);
  50162. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50163. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50164. if (d < 0)
  50165. return false;
  50166. pc.subtractToRef(point, this._tempVector3);
  50167. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50168. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50169. if (d < 0)
  50170. return false;
  50171. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50172. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50173. return d >= 0;
  50174. };
  50175. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50176. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50177. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50178. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50179. return false;
  50180. }
  50181. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50182. return false;
  50183. return true;
  50184. };
  50185. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50186. var t0;
  50187. var embeddedInPlane = false;
  50188. //defensive programming, actually not needed.
  50189. if (!trianglePlaneArray) {
  50190. trianglePlaneArray = [];
  50191. }
  50192. if (!trianglePlaneArray[faceIndex]) {
  50193. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50194. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50195. }
  50196. var trianglePlane = trianglePlaneArray[faceIndex];
  50197. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50198. return;
  50199. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50200. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50201. if (normalDotVelocity == 0) {
  50202. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50203. return;
  50204. embeddedInPlane = true;
  50205. t0 = 0;
  50206. }
  50207. else {
  50208. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50209. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50210. if (t0 > t1) {
  50211. var temp = t1;
  50212. t1 = t0;
  50213. t0 = temp;
  50214. }
  50215. if (t0 > 1.0 || t1 < 0.0)
  50216. return;
  50217. if (t0 < 0)
  50218. t0 = 0;
  50219. if (t0 > 1.0)
  50220. t0 = 1.0;
  50221. }
  50222. this._collisionPoint.copyFromFloats(0, 0, 0);
  50223. var found = false;
  50224. var t = 1.0;
  50225. if (!embeddedInPlane) {
  50226. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50227. this._velocity.scaleToRef(t0, this._tempVector);
  50228. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50229. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50230. found = true;
  50231. t = t0;
  50232. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50233. }
  50234. }
  50235. if (!found) {
  50236. var velocitySquaredLength = this._velocity.lengthSquared();
  50237. var a = velocitySquaredLength;
  50238. this._basePoint.subtractToRef(p1, this._tempVector);
  50239. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50240. var c = this._tempVector.lengthSquared() - 1.0;
  50241. var lowestRoot = getLowestRoot(a, b, c, t);
  50242. if (lowestRoot.found) {
  50243. t = lowestRoot.root;
  50244. found = true;
  50245. this._collisionPoint.copyFrom(p1);
  50246. }
  50247. this._basePoint.subtractToRef(p2, this._tempVector);
  50248. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50249. c = this._tempVector.lengthSquared() - 1.0;
  50250. lowestRoot = getLowestRoot(a, b, c, t);
  50251. if (lowestRoot.found) {
  50252. t = lowestRoot.root;
  50253. found = true;
  50254. this._collisionPoint.copyFrom(p2);
  50255. }
  50256. this._basePoint.subtractToRef(p3, this._tempVector);
  50257. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50258. c = this._tempVector.lengthSquared() - 1.0;
  50259. lowestRoot = getLowestRoot(a, b, c, t);
  50260. if (lowestRoot.found) {
  50261. t = lowestRoot.root;
  50262. found = true;
  50263. this._collisionPoint.copyFrom(p3);
  50264. }
  50265. p2.subtractToRef(p1, this._edge);
  50266. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50267. var edgeSquaredLength = this._edge.lengthSquared();
  50268. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50269. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50270. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50271. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50272. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50273. lowestRoot = getLowestRoot(a, b, c, t);
  50274. if (lowestRoot.found) {
  50275. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50276. if (f >= 0.0 && f <= 1.0) {
  50277. t = lowestRoot.root;
  50278. found = true;
  50279. this._edge.scaleInPlace(f);
  50280. p1.addToRef(this._edge, this._collisionPoint);
  50281. }
  50282. }
  50283. p3.subtractToRef(p2, this._edge);
  50284. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50285. edgeSquaredLength = this._edge.lengthSquared();
  50286. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50287. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50288. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50289. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50290. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50291. lowestRoot = getLowestRoot(a, b, c, t);
  50292. if (lowestRoot.found) {
  50293. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50294. if (f >= 0.0 && f <= 1.0) {
  50295. t = lowestRoot.root;
  50296. found = true;
  50297. this._edge.scaleInPlace(f);
  50298. p2.addToRef(this._edge, this._collisionPoint);
  50299. }
  50300. }
  50301. p1.subtractToRef(p3, this._edge);
  50302. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50303. edgeSquaredLength = this._edge.lengthSquared();
  50304. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50305. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50306. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50307. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50308. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50309. lowestRoot = getLowestRoot(a, b, c, t);
  50310. if (lowestRoot.found) {
  50311. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50312. if (f >= 0.0 && f <= 1.0) {
  50313. t = lowestRoot.root;
  50314. found = true;
  50315. this._edge.scaleInPlace(f);
  50316. p3.addToRef(this._edge, this._collisionPoint);
  50317. }
  50318. }
  50319. }
  50320. if (found) {
  50321. var distToCollision = t * this._velocity.length();
  50322. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50323. if (!this.intersectionPoint) {
  50324. this.intersectionPoint = this._collisionPoint.clone();
  50325. }
  50326. else {
  50327. this.intersectionPoint.copyFrom(this._collisionPoint);
  50328. }
  50329. this._nearestDistance = distToCollision;
  50330. this.collisionFound = true;
  50331. }
  50332. }
  50333. };
  50334. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50335. for (var i = indexStart; i < indexEnd; i += 3) {
  50336. var p1 = pts[indices[i] - decal];
  50337. var p2 = pts[indices[i + 1] - decal];
  50338. var p3 = pts[indices[i + 2] - decal];
  50339. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50340. }
  50341. };
  50342. Collider.prototype._getResponse = function (pos, vel) {
  50343. pos.addToRef(vel, this._destinationPoint);
  50344. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50345. this._basePoint.addToRef(vel, pos);
  50346. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50347. this._slidePlaneNormal.normalize();
  50348. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50349. pos.addInPlace(this._displacementVector);
  50350. this.intersectionPoint.addInPlace(this._displacementVector);
  50351. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50352. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50353. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50354. };
  50355. return Collider;
  50356. }());
  50357. BABYLON.Collider = Collider;
  50358. })(BABYLON || (BABYLON = {}));
  50359. //# sourceMappingURL=babylon.collider.js.map
  50360. var BABYLON;
  50361. (function (BABYLON) {
  50362. //WebWorker code will be inserted to this variable.
  50363. BABYLON.CollisionWorker = "";
  50364. var WorkerTaskType;
  50365. (function (WorkerTaskType) {
  50366. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50367. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50368. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50369. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50370. var WorkerReplyType;
  50371. (function (WorkerReplyType) {
  50372. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50373. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50374. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50375. var CollisionCoordinatorWorker = /** @class */ (function () {
  50376. function CollisionCoordinatorWorker() {
  50377. var _this = this;
  50378. this._scaledPosition = BABYLON.Vector3.Zero();
  50379. this._scaledVelocity = BABYLON.Vector3.Zero();
  50380. this.onMeshUpdated = function (transformNode) {
  50381. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50382. };
  50383. this.onGeometryUpdated = function (geometry) {
  50384. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50385. };
  50386. this._afterRender = function () {
  50387. if (!_this._init)
  50388. return;
  50389. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50390. return;
  50391. }
  50392. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50393. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50394. if (_this._runningUpdated > 4) {
  50395. return;
  50396. }
  50397. ++_this._runningUpdated;
  50398. var payload = {
  50399. updatedMeshes: _this._addUpdateMeshesList,
  50400. updatedGeometries: _this._addUpdateGeometriesList,
  50401. removedGeometries: _this._toRemoveGeometryArray,
  50402. removedMeshes: _this._toRemoveMeshesArray
  50403. };
  50404. var message = {
  50405. payload: payload,
  50406. taskType: WorkerTaskType.UPDATE
  50407. };
  50408. var serializable = [];
  50409. for (var id in payload.updatedGeometries) {
  50410. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50411. //prepare transferables
  50412. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50413. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50414. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50415. }
  50416. }
  50417. _this._worker.postMessage(message, serializable);
  50418. _this._addUpdateMeshesList = {};
  50419. _this._addUpdateGeometriesList = {};
  50420. _this._toRemoveGeometryArray = [];
  50421. _this._toRemoveMeshesArray = [];
  50422. };
  50423. this._onMessageFromWorker = function (e) {
  50424. var returnData = e.data;
  50425. if (returnData.error != WorkerReplyType.SUCCESS) {
  50426. //TODO what errors can be returned from the worker?
  50427. BABYLON.Tools.Warn("error returned from worker!");
  50428. return;
  50429. }
  50430. switch (returnData.taskType) {
  50431. case WorkerTaskType.INIT:
  50432. _this._init = true;
  50433. //Update the worked with ALL of the scene's current state
  50434. _this._scene.meshes.forEach(function (mesh) {
  50435. _this.onMeshAdded(mesh);
  50436. });
  50437. _this._scene.getGeometries().forEach(function (geometry) {
  50438. _this.onGeometryAdded(geometry);
  50439. });
  50440. break;
  50441. case WorkerTaskType.UPDATE:
  50442. _this._runningUpdated--;
  50443. break;
  50444. case WorkerTaskType.COLLIDE:
  50445. var returnPayload = returnData.payload;
  50446. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50447. return;
  50448. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50449. if (callback) {
  50450. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50451. if (mesh) {
  50452. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50453. }
  50454. }
  50455. //cleanup
  50456. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50457. break;
  50458. }
  50459. };
  50460. this._collisionsCallbackArray = [];
  50461. this._init = false;
  50462. this._runningUpdated = 0;
  50463. this._addUpdateMeshesList = {};
  50464. this._addUpdateGeometriesList = {};
  50465. this._toRemoveGeometryArray = [];
  50466. this._toRemoveMeshesArray = [];
  50467. }
  50468. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50469. if (!this._init)
  50470. return;
  50471. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50472. return;
  50473. position.divideToRef(collider._radius, this._scaledPosition);
  50474. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50475. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50476. var payload = {
  50477. collider: {
  50478. position: this._scaledPosition.asArray(),
  50479. velocity: this._scaledVelocity.asArray(),
  50480. radius: collider._radius.asArray()
  50481. },
  50482. collisionId: collisionIndex,
  50483. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50484. maximumRetry: maximumRetry
  50485. };
  50486. var message = {
  50487. payload: payload,
  50488. taskType: WorkerTaskType.COLLIDE
  50489. };
  50490. this._worker.postMessage(message);
  50491. };
  50492. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50493. this._scene = scene;
  50494. this._scene.registerAfterRender(this._afterRender);
  50495. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50496. this._worker = new Worker(workerUrl);
  50497. this._worker.onmessage = this._onMessageFromWorker;
  50498. var message = {
  50499. payload: {},
  50500. taskType: WorkerTaskType.INIT
  50501. };
  50502. this._worker.postMessage(message);
  50503. };
  50504. CollisionCoordinatorWorker.prototype.destroy = function () {
  50505. this._scene.unregisterAfterRender(this._afterRender);
  50506. this._worker.terminate();
  50507. };
  50508. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50509. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50510. this.onMeshUpdated(mesh);
  50511. };
  50512. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50513. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50514. };
  50515. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50516. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50517. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50518. this.onGeometryUpdated(geometry);
  50519. };
  50520. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50521. this._toRemoveGeometryArray.push(geometry.id);
  50522. };
  50523. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50524. var submeshes = [];
  50525. if (mesh.subMeshes) {
  50526. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50527. var boundingInfo = sm.getBoundingInfo();
  50528. return {
  50529. position: idx,
  50530. verticesStart: sm.verticesStart,
  50531. verticesCount: sm.verticesCount,
  50532. indexStart: sm.indexStart,
  50533. indexCount: sm.indexCount,
  50534. hasMaterial: !!sm.getMaterial(),
  50535. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50536. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50537. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50538. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50539. };
  50540. });
  50541. }
  50542. var geometryId = null;
  50543. if (mesh instanceof BABYLON.Mesh) {
  50544. var geometry = mesh.geometry;
  50545. geometryId = geometry ? geometry.id : null;
  50546. }
  50547. else if (mesh instanceof BABYLON.InstancedMesh) {
  50548. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50549. geometryId = geometry ? geometry.id : null;
  50550. }
  50551. var boundingInfo = mesh.getBoundingInfo();
  50552. return {
  50553. uniqueId: mesh.uniqueId,
  50554. id: mesh.id,
  50555. name: mesh.name,
  50556. geometryId: geometryId,
  50557. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50558. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50559. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50560. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50561. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50562. subMeshes: submeshes,
  50563. checkCollisions: mesh.checkCollisions
  50564. };
  50565. };
  50566. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50567. return {
  50568. id: geometry.id,
  50569. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50570. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50571. indices: new Uint32Array(geometry.getIndices() || []),
  50572. };
  50573. };
  50574. return CollisionCoordinatorWorker;
  50575. }());
  50576. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50577. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50578. function CollisionCoordinatorLegacy() {
  50579. this._scaledPosition = BABYLON.Vector3.Zero();
  50580. this._scaledVelocity = BABYLON.Vector3.Zero();
  50581. this._finalPosition = BABYLON.Vector3.Zero();
  50582. }
  50583. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50584. position.divideToRef(collider._radius, this._scaledPosition);
  50585. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50586. collider.collidedMesh = null;
  50587. collider._retry = 0;
  50588. collider._initialVelocity = this._scaledVelocity;
  50589. collider._initialPosition = this._scaledPosition;
  50590. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50591. this._finalPosition.multiplyInPlace(collider._radius);
  50592. //run the callback
  50593. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50594. };
  50595. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50596. this._scene = scene;
  50597. };
  50598. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50599. //Legacy need no destruction method.
  50600. };
  50601. //No update in legacy mode
  50602. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50603. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50604. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50605. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50606. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50607. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50608. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50609. if (excludedMesh === void 0) { excludedMesh = null; }
  50610. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50611. if (collider._retry >= maximumRetry) {
  50612. finalPosition.copyFrom(position);
  50613. return;
  50614. }
  50615. // Check if this is a mesh else camera or -1
  50616. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50617. collider._initialize(position, velocity, closeDistance);
  50618. // Check all meshes
  50619. for (var index = 0; index < this._scene.meshes.length; index++) {
  50620. var mesh = this._scene.meshes[index];
  50621. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50622. mesh._checkCollision(collider);
  50623. }
  50624. }
  50625. if (!collider.collisionFound) {
  50626. position.addToRef(velocity, finalPosition);
  50627. return;
  50628. }
  50629. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50630. collider._getResponse(position, velocity);
  50631. }
  50632. if (velocity.length() <= closeDistance) {
  50633. finalPosition.copyFrom(position);
  50634. return;
  50635. }
  50636. collider._retry++;
  50637. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50638. };
  50639. return CollisionCoordinatorLegacy;
  50640. }());
  50641. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50642. })(BABYLON || (BABYLON = {}));
  50643. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50644. var BABYLON;
  50645. (function (BABYLON) {
  50646. /**
  50647. * A particle represents one of the element emitted by a particle system.
  50648. * This is mainly define by its coordinates, direction, velocity and age.
  50649. */
  50650. var Particle = /** @class */ (function () {
  50651. /**
  50652. * Creates a new instance of @see Particle
  50653. * @param particleSystem the particle system the particle belongs to
  50654. */
  50655. function Particle(
  50656. /**
  50657. * particleSystem the particle system the particle belongs to.
  50658. */
  50659. particleSystem) {
  50660. this.particleSystem = particleSystem;
  50661. /**
  50662. * The world position of the particle in the scene.
  50663. */
  50664. this.position = BABYLON.Vector3.Zero();
  50665. /**
  50666. * The world direction of the particle in the scene.
  50667. */
  50668. this.direction = BABYLON.Vector3.Zero();
  50669. /**
  50670. * The color of the particle.
  50671. */
  50672. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50673. /**
  50674. * The color change of the particle per step.
  50675. */
  50676. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50677. /**
  50678. * Defines how long will the life of the particle be.
  50679. */
  50680. this.lifeTime = 1.0;
  50681. /**
  50682. * The current age of the particle.
  50683. */
  50684. this.age = 0;
  50685. /**
  50686. * The current size of the particle.
  50687. */
  50688. this.size = 0;
  50689. /**
  50690. * The current angle of the particle.
  50691. */
  50692. this.angle = 0;
  50693. /**
  50694. * Defines how fast is the angle changing.
  50695. */
  50696. this.angularSpeed = 0;
  50697. /**
  50698. * Defines the cell index used by the particle to be rendered from a sprite.
  50699. */
  50700. this.cellIndex = 0;
  50701. this._currentFrameCounter = 0;
  50702. if (!this.particleSystem.isAnimationSheetEnabled) {
  50703. return;
  50704. }
  50705. this.updateCellInfoFromSystem();
  50706. }
  50707. Particle.prototype.updateCellInfoFromSystem = function () {
  50708. this.cellIndex = this.particleSystem.startSpriteCellID;
  50709. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50710. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  50711. }
  50712. else {
  50713. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  50714. }
  50715. };
  50716. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50717. // (ageOffset / scaledUpdateSpeed) / available cells
  50718. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50719. this._currentFrameCounter += scaledUpdateSpeed;
  50720. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50721. this._currentFrameCounter = 0;
  50722. this.cellIndex++;
  50723. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50724. this.cellIndex = this.particleSystem.endSpriteCellID;
  50725. }
  50726. }
  50727. };
  50728. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  50729. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50730. this.cellIndex++;
  50731. this._currentFrameCounter = 0;
  50732. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50733. if (this.particleSystem.spriteCellLoop) {
  50734. this.cellIndex = this.particleSystem.startSpriteCellID;
  50735. }
  50736. else {
  50737. this.cellIndex = this.particleSystem.endSpriteCellID;
  50738. }
  50739. }
  50740. }
  50741. else {
  50742. this._currentFrameCounter++;
  50743. }
  50744. };
  50745. /**
  50746. * Copy the properties of particle to another one.
  50747. * @param other the particle to copy the information to.
  50748. */
  50749. Particle.prototype.copyTo = function (other) {
  50750. other.position.copyFrom(this.position);
  50751. other.direction.copyFrom(this.direction);
  50752. other.color.copyFrom(this.color);
  50753. other.colorStep.copyFrom(this.colorStep);
  50754. other.lifeTime = this.lifeTime;
  50755. other.age = this.age;
  50756. other.size = this.size;
  50757. other.angle = this.angle;
  50758. other.angularSpeed = this.angularSpeed;
  50759. other.particleSystem = this.particleSystem;
  50760. other.cellIndex = this.cellIndex;
  50761. };
  50762. return Particle;
  50763. }());
  50764. BABYLON.Particle = Particle;
  50765. })(BABYLON || (BABYLON = {}));
  50766. //# sourceMappingURL=babylon.particle.js.map
  50767. var BABYLON;
  50768. (function (BABYLON) {
  50769. /**
  50770. * This represents a particle system in Babylon.
  50771. * 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.
  50772. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50773. * @example https://doc.babylonjs.com/babylon101/particles
  50774. */
  50775. var ParticleSystem = /** @class */ (function () {
  50776. /**
  50777. * Instantiates a particle system.
  50778. * 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.
  50779. * @param name The name of the particle system
  50780. * @param capacity The max number of particles alive at the same time
  50781. * @param scene The scene the particle system belongs to
  50782. * @param customEffect a custom effect used to change the way particles are rendered by default
  50783. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50784. * @param epsilon Offset used to render the particles
  50785. */
  50786. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50787. if (customEffect === void 0) { customEffect = null; }
  50788. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50789. if (epsilon === void 0) { epsilon = 0.01; }
  50790. var _this = this;
  50791. /**
  50792. * List of animations used by the particle system.
  50793. */
  50794. this.animations = [];
  50795. /**
  50796. * The rendering group used by the Particle system to chose when to render.
  50797. */
  50798. this.renderingGroupId = 0;
  50799. /**
  50800. * The emitter represents the Mesh or position we are attaching the particle system to.
  50801. */
  50802. this.emitter = null;
  50803. /**
  50804. * The maximum number of particles to emit per frame
  50805. */
  50806. this.emitRate = 10;
  50807. /**
  50808. * If you want to launch only a few particles at once, that can be done, as well.
  50809. */
  50810. this.manualEmitCount = -1;
  50811. /**
  50812. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50813. */
  50814. this.updateSpeed = 0.01;
  50815. /**
  50816. * The amount of time the particle system is running (depends of the overall update speed).
  50817. */
  50818. this.targetStopDuration = 0;
  50819. /**
  50820. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50821. */
  50822. this.disposeOnStop = false;
  50823. /**
  50824. * Minimum power of emitting particles.
  50825. */
  50826. this.minEmitPower = 1;
  50827. /**
  50828. * Maximum power of emitting particles.
  50829. */
  50830. this.maxEmitPower = 1;
  50831. /**
  50832. * Minimum life time of emitting particles.
  50833. */
  50834. this.minLifeTime = 1;
  50835. /**
  50836. * Maximum life time of emitting particles.
  50837. */
  50838. this.maxLifeTime = 1;
  50839. /**
  50840. * Minimum Size of emitting particles.
  50841. */
  50842. this.minSize = 1;
  50843. /**
  50844. * Maximum Size of emitting particles.
  50845. */
  50846. this.maxSize = 1;
  50847. /**
  50848. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50849. */
  50850. this.minAngularSpeed = 0;
  50851. /**
  50852. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50853. */
  50854. this.maxAngularSpeed = 0;
  50855. /**
  50856. * The layer mask we are rendering the particles through.
  50857. */
  50858. this.layerMask = 0x0FFFFFFF;
  50859. /**
  50860. * This can help using your own shader to render the particle system.
  50861. * The according effect will be created
  50862. */
  50863. this.customShader = null;
  50864. /**
  50865. * By default particle system starts as soon as they are created. This prevents the
  50866. * automatic start to happen and let you decide when to start emitting particles.
  50867. */
  50868. this.preventAutoStart = false;
  50869. /**
  50870. * Callback triggered when the particle animation is ending.
  50871. */
  50872. this.onAnimationEnd = null;
  50873. /**
  50874. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50875. */
  50876. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50877. /**
  50878. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50879. * to override the particles.
  50880. */
  50881. this.forceDepthWrite = false;
  50882. /**
  50883. * You can use gravity if you want to give an orientation to your particles.
  50884. */
  50885. this.gravity = BABYLON.Vector3.Zero();
  50886. /**
  50887. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50888. */
  50889. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50890. /**
  50891. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50892. */
  50893. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50894. /**
  50895. * Color the particle will have at the end of its lifetime.
  50896. */
  50897. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50898. /**
  50899. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50900. */
  50901. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50902. /**
  50903. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50904. */
  50905. this.spriteCellLoop = true;
  50906. /**
  50907. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50908. */
  50909. this.spriteCellChangeSpeed = 0;
  50910. /**
  50911. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50912. */
  50913. this.startSpriteCellID = 0;
  50914. /**
  50915. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50916. */
  50917. this.endSpriteCellID = 0;
  50918. /**
  50919. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50920. */
  50921. this.spriteCellWidth = 0;
  50922. /**
  50923. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50924. */
  50925. this.spriteCellHeight = 0;
  50926. /**
  50927. * An event triggered when the system is disposed.
  50928. */
  50929. this.onDisposeObservable = new BABYLON.Observable();
  50930. this._particles = new Array();
  50931. this._stockParticles = new Array();
  50932. this._newPartsExcess = 0;
  50933. this._vertexBuffers = {};
  50934. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50935. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50936. this._scaledDirection = BABYLON.Vector3.Zero();
  50937. this._scaledGravity = BABYLON.Vector3.Zero();
  50938. this._currentRenderId = -1;
  50939. this._started = false;
  50940. this._stopped = false;
  50941. this._actualFrame = 0;
  50942. this._vertexBufferSize = 11;
  50943. // start of sub system methods
  50944. /**
  50945. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50946. * Its lifetime will start back at 0.
  50947. */
  50948. this.recycleParticle = function (particle) {
  50949. var lastParticle = _this._particles.pop();
  50950. if (lastParticle !== particle) {
  50951. lastParticle.copyTo(particle);
  50952. }
  50953. _this._stockParticles.push(lastParticle);
  50954. };
  50955. this._createParticle = function () {
  50956. var particle;
  50957. if (_this._stockParticles.length !== 0) {
  50958. particle = _this._stockParticles.pop();
  50959. particle.age = 0;
  50960. particle.cellIndex = _this.startSpriteCellID;
  50961. }
  50962. else {
  50963. particle = new BABYLON.Particle(_this);
  50964. }
  50965. return particle;
  50966. };
  50967. this._emitFromParticle = function (particle) {
  50968. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  50969. return;
  50970. }
  50971. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  50972. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  50973. subSystem._rootParticleSystem = _this;
  50974. _this.activeSubSystems.push(subSystem);
  50975. subSystem.start();
  50976. };
  50977. this._appendParticleVertexes = null;
  50978. this.id = name;
  50979. this.name = name;
  50980. this._capacity = capacity;
  50981. this._epsilon = epsilon;
  50982. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50983. if (isAnimationSheetEnabled) {
  50984. this._vertexBufferSize = 12;
  50985. }
  50986. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50987. this._customEffect = customEffect;
  50988. scene.particleSystems.push(this);
  50989. this._createIndexBuffer();
  50990. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50991. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50992. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50993. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50994. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50995. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50996. if (this._isAnimationSheetEnabled) {
  50997. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50998. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50999. }
  51000. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51001. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51002. this._vertexBuffers["options"] = options;
  51003. // Default emitter type
  51004. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51005. this.updateFunction = function (particles) {
  51006. for (var index = 0; index < particles.length; index++) {
  51007. var particle = particles[index];
  51008. particle.age += _this._scaledUpdateSpeed;
  51009. if (particle.age >= particle.lifeTime) {
  51010. _this._emitFromParticle(particle);
  51011. _this.recycleParticle(particle);
  51012. index--;
  51013. continue;
  51014. }
  51015. else {
  51016. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51017. particle.color.addInPlace(_this._scaledColorStep);
  51018. if (particle.color.a < 0)
  51019. particle.color.a = 0;
  51020. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51021. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51022. particle.position.addInPlace(_this._scaledDirection);
  51023. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51024. particle.direction.addInPlace(_this._scaledGravity);
  51025. if (_this._isAnimationSheetEnabled) {
  51026. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51027. }
  51028. }
  51029. }
  51030. };
  51031. }
  51032. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51033. /**
  51034. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51035. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51036. */
  51037. get: function () {
  51038. if (this.particleEmitterType.direction1) {
  51039. return this.particleEmitterType.direction1;
  51040. }
  51041. return BABYLON.Vector3.Zero();
  51042. },
  51043. set: function (value) {
  51044. if (this.particleEmitterType.direction1) {
  51045. this.particleEmitterType.direction1 = value;
  51046. }
  51047. },
  51048. enumerable: true,
  51049. configurable: true
  51050. });
  51051. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51052. /**
  51053. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51054. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51055. */
  51056. get: function () {
  51057. if (this.particleEmitterType.direction2) {
  51058. return this.particleEmitterType.direction2;
  51059. }
  51060. return BABYLON.Vector3.Zero();
  51061. },
  51062. set: function (value) {
  51063. if (this.particleEmitterType.direction2) {
  51064. this.particleEmitterType.direction2 = value;
  51065. }
  51066. },
  51067. enumerable: true,
  51068. configurable: true
  51069. });
  51070. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51071. /**
  51072. * 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.
  51073. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51074. */
  51075. get: function () {
  51076. if (this.particleEmitterType.minEmitBox) {
  51077. return this.particleEmitterType.minEmitBox;
  51078. }
  51079. return BABYLON.Vector3.Zero();
  51080. },
  51081. set: function (value) {
  51082. if (this.particleEmitterType.minEmitBox) {
  51083. this.particleEmitterType.minEmitBox = value;
  51084. }
  51085. },
  51086. enumerable: true,
  51087. configurable: true
  51088. });
  51089. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51090. /**
  51091. * 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.
  51092. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51093. */
  51094. get: function () {
  51095. if (this.particleEmitterType.maxEmitBox) {
  51096. return this.particleEmitterType.maxEmitBox;
  51097. }
  51098. return BABYLON.Vector3.Zero();
  51099. },
  51100. set: function (value) {
  51101. if (this.particleEmitterType.maxEmitBox) {
  51102. this.particleEmitterType.maxEmitBox = value;
  51103. }
  51104. },
  51105. enumerable: true,
  51106. configurable: true
  51107. });
  51108. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51109. /**
  51110. * Sets a callback that will be triggered when the system is disposed.
  51111. */
  51112. set: function (callback) {
  51113. if (this._onDisposeObserver) {
  51114. this.onDisposeObservable.remove(this._onDisposeObserver);
  51115. }
  51116. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51117. },
  51118. enumerable: true,
  51119. configurable: true
  51120. });
  51121. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51122. /**
  51123. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51124. */
  51125. get: function () {
  51126. return this._isAnimationSheetEnabled;
  51127. },
  51128. enumerable: true,
  51129. configurable: true
  51130. });
  51131. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51132. //end of Sub-emitter
  51133. /**
  51134. * Gets the current list of active particles
  51135. */
  51136. get: function () {
  51137. return this._particles;
  51138. },
  51139. enumerable: true,
  51140. configurable: true
  51141. });
  51142. /**
  51143. * Returns the string "ParticleSystem"
  51144. * @returns a string containing the class name
  51145. */
  51146. ParticleSystem.prototype.getClassName = function () {
  51147. return "ParticleSystem";
  51148. };
  51149. ParticleSystem.prototype._createIndexBuffer = function () {
  51150. var indices = [];
  51151. var index = 0;
  51152. for (var count = 0; count < this._capacity; count++) {
  51153. indices.push(index);
  51154. indices.push(index + 1);
  51155. indices.push(index + 2);
  51156. indices.push(index);
  51157. indices.push(index + 2);
  51158. indices.push(index + 3);
  51159. index += 4;
  51160. }
  51161. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51162. };
  51163. /**
  51164. * Gets the maximum number of particles active at the same time.
  51165. * @returns The max number of active particles.
  51166. */
  51167. ParticleSystem.prototype.getCapacity = function () {
  51168. return this._capacity;
  51169. };
  51170. /**
  51171. * Gets Wether there are still active particles in the system.
  51172. * @returns True if it is alive, otherwise false.
  51173. */
  51174. ParticleSystem.prototype.isAlive = function () {
  51175. return this._alive;
  51176. };
  51177. /**
  51178. * Gets Wether the system has been started.
  51179. * @returns True if it has been started, otherwise false.
  51180. */
  51181. ParticleSystem.prototype.isStarted = function () {
  51182. return this._started;
  51183. };
  51184. /**
  51185. * Starts the particle system and begins to emit.
  51186. */
  51187. ParticleSystem.prototype.start = function () {
  51188. this._started = true;
  51189. this._stopped = false;
  51190. this._actualFrame = 0;
  51191. if (this.subEmitters && this.subEmitters.length != 0) {
  51192. this.activeSubSystems = new Array();
  51193. }
  51194. };
  51195. /**
  51196. * Stops the particle system.
  51197. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  51198. */
  51199. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51200. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51201. this._stopped = true;
  51202. if (stopSubEmitters) {
  51203. this._stopSubEmitters();
  51204. }
  51205. };
  51206. // animation sheet
  51207. /**
  51208. * Remove all active particles
  51209. */
  51210. ParticleSystem.prototype.reset = function () {
  51211. this._stockParticles = [];
  51212. this._particles = [];
  51213. };
  51214. /**
  51215. * @ignore (for internal use only)
  51216. */
  51217. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51218. var offset = index * this._vertexBufferSize;
  51219. this._vertexData[offset] = particle.position.x;
  51220. this._vertexData[offset + 1] = particle.position.y;
  51221. this._vertexData[offset + 2] = particle.position.z;
  51222. this._vertexData[offset + 3] = particle.color.r;
  51223. this._vertexData[offset + 4] = particle.color.g;
  51224. this._vertexData[offset + 5] = particle.color.b;
  51225. this._vertexData[offset + 6] = particle.color.a;
  51226. this._vertexData[offset + 7] = particle.angle;
  51227. this._vertexData[offset + 8] = particle.size;
  51228. this._vertexData[offset + 9] = offsetX;
  51229. this._vertexData[offset + 10] = offsetY;
  51230. };
  51231. /**
  51232. * @ignore (for internal use only)
  51233. */
  51234. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51235. if (offsetX === 0)
  51236. offsetX = this._epsilon;
  51237. else if (offsetX === 1)
  51238. offsetX = 1 - this._epsilon;
  51239. if (offsetY === 0)
  51240. offsetY = this._epsilon;
  51241. else if (offsetY === 1)
  51242. offsetY = 1 - this._epsilon;
  51243. var offset = index * this._vertexBufferSize;
  51244. this._vertexData[offset] = particle.position.x;
  51245. this._vertexData[offset + 1] = particle.position.y;
  51246. this._vertexData[offset + 2] = particle.position.z;
  51247. this._vertexData[offset + 3] = particle.color.r;
  51248. this._vertexData[offset + 4] = particle.color.g;
  51249. this._vertexData[offset + 5] = particle.color.b;
  51250. this._vertexData[offset + 6] = particle.color.a;
  51251. this._vertexData[offset + 7] = particle.angle;
  51252. this._vertexData[offset + 8] = particle.size;
  51253. this._vertexData[offset + 9] = offsetX;
  51254. this._vertexData[offset + 10] = offsetY;
  51255. this._vertexData[offset + 11] = particle.cellIndex;
  51256. };
  51257. ParticleSystem.prototype._stopSubEmitters = function () {
  51258. if (!this.activeSubSystems) {
  51259. return;
  51260. }
  51261. this.activeSubSystems.forEach(function (subSystem) {
  51262. subSystem.stop(true);
  51263. });
  51264. this.activeSubSystems = new Array();
  51265. };
  51266. ParticleSystem.prototype._removeFromRoot = function () {
  51267. if (!this._rootParticleSystem) {
  51268. return;
  51269. }
  51270. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  51271. if (index !== -1) {
  51272. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  51273. }
  51274. };
  51275. // end of sub system methods
  51276. ParticleSystem.prototype._update = function (newParticles) {
  51277. // Update current
  51278. this._alive = this._particles.length > 0;
  51279. this.updateFunction(this._particles);
  51280. // Add new ones
  51281. var worldMatrix;
  51282. if (this.emitter.position) {
  51283. var emitterMesh = this.emitter;
  51284. worldMatrix = emitterMesh.getWorldMatrix();
  51285. }
  51286. else {
  51287. var emitterPosition = this.emitter;
  51288. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51289. }
  51290. var particle;
  51291. for (var index = 0; index < newParticles; index++) {
  51292. if (this._particles.length === this._capacity) {
  51293. break;
  51294. }
  51295. particle = this._createParticle();
  51296. this._particles.push(particle);
  51297. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51298. if (this.startPositionFunction) {
  51299. this.startPositionFunction(worldMatrix, particle.position, particle);
  51300. }
  51301. else {
  51302. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51303. }
  51304. if (this.startDirectionFunction) {
  51305. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51306. }
  51307. else {
  51308. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51309. }
  51310. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51311. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51312. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51313. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51314. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51315. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51316. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51317. }
  51318. };
  51319. ParticleSystem.prototype._getEffect = function () {
  51320. if (this._customEffect) {
  51321. return this._customEffect;
  51322. }
  51323. ;
  51324. var defines = [];
  51325. if (this._scene.clipPlane) {
  51326. defines.push("#define CLIPPLANE");
  51327. }
  51328. if (this._isAnimationSheetEnabled) {
  51329. defines.push("#define ANIMATESHEET");
  51330. }
  51331. // Effect
  51332. var join = defines.join("\n");
  51333. if (this._cachedDefines !== join) {
  51334. this._cachedDefines = join;
  51335. var attributesNamesOrOptions;
  51336. var effectCreationOption;
  51337. if (this._isAnimationSheetEnabled) {
  51338. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51339. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51340. }
  51341. else {
  51342. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51343. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51344. }
  51345. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51346. }
  51347. return this._effect;
  51348. };
  51349. /**
  51350. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51351. */
  51352. ParticleSystem.prototype.animate = function () {
  51353. if (!this._started)
  51354. return;
  51355. var effect = this._getEffect();
  51356. // Check
  51357. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51358. return;
  51359. if (this._currentRenderId === this._scene.getRenderId()) {
  51360. return;
  51361. }
  51362. this._currentRenderId = this._scene.getRenderId();
  51363. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51364. // determine the number of particles we need to create
  51365. var newParticles;
  51366. if (this.manualEmitCount > -1) {
  51367. newParticles = this.manualEmitCount;
  51368. this._newPartsExcess = 0;
  51369. this.manualEmitCount = 0;
  51370. }
  51371. else {
  51372. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51373. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51374. }
  51375. if (this._newPartsExcess > 1.0) {
  51376. newParticles += this._newPartsExcess >> 0;
  51377. this._newPartsExcess -= this._newPartsExcess >> 0;
  51378. }
  51379. this._alive = false;
  51380. if (!this._stopped) {
  51381. this._actualFrame += this._scaledUpdateSpeed;
  51382. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51383. this.stop();
  51384. }
  51385. else {
  51386. newParticles = 0;
  51387. }
  51388. this._update(newParticles);
  51389. // Stopped?
  51390. if (this._stopped) {
  51391. if (!this._alive) {
  51392. this._started = false;
  51393. if (this.onAnimationEnd) {
  51394. this.onAnimationEnd();
  51395. }
  51396. if (this.disposeOnStop) {
  51397. this._scene._toBeDisposed.push(this);
  51398. }
  51399. }
  51400. }
  51401. // Animation sheet
  51402. if (this._isAnimationSheetEnabled) {
  51403. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51404. }
  51405. else {
  51406. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51407. }
  51408. // Update VBO
  51409. var offset = 0;
  51410. for (var index = 0; index < this._particles.length; index++) {
  51411. var particle = this._particles[index];
  51412. this._appendParticleVertexes(offset, particle);
  51413. offset += 4;
  51414. }
  51415. if (this._vertexBuffer) {
  51416. this._vertexBuffer.update(this._vertexData);
  51417. }
  51418. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  51419. this.stop();
  51420. }
  51421. };
  51422. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51423. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51424. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51425. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51426. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51427. };
  51428. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51429. this._appendParticleVertex(offset++, particle, 0, 0);
  51430. this._appendParticleVertex(offset++, particle, 1, 0);
  51431. this._appendParticleVertex(offset++, particle, 1, 1);
  51432. this._appendParticleVertex(offset++, particle, 0, 1);
  51433. };
  51434. /**
  51435. * Rebuilds the particle system.
  51436. */
  51437. ParticleSystem.prototype.rebuild = function () {
  51438. this._createIndexBuffer();
  51439. if (this._vertexBuffer) {
  51440. this._vertexBuffer._rebuild();
  51441. }
  51442. };
  51443. /**
  51444. * Is this system ready to be used/rendered
  51445. * @return true if the system is ready
  51446. */
  51447. ParticleSystem.prototype.isReady = function () {
  51448. var effect = this._getEffect();
  51449. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  51450. return false;
  51451. }
  51452. return true;
  51453. };
  51454. /**
  51455. * Renders the particle system in its current state.
  51456. * @returns the current number of particles
  51457. */
  51458. ParticleSystem.prototype.render = function () {
  51459. var effect = this._getEffect();
  51460. // Check
  51461. if (!this.isReady() || !this._particles.length) {
  51462. return 0;
  51463. }
  51464. var engine = this._scene.getEngine();
  51465. // Render
  51466. engine.enableEffect(effect);
  51467. engine.setState(false);
  51468. var viewMatrix = this._scene.getViewMatrix();
  51469. effect.setTexture("diffuseSampler", this.particleTexture);
  51470. effect.setMatrix("view", viewMatrix);
  51471. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51472. if (this._isAnimationSheetEnabled && this.particleTexture) {
  51473. var baseSize = this.particleTexture.getBaseSize();
  51474. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51475. }
  51476. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51477. if (this._scene.clipPlane) {
  51478. var clipPlane = this._scene.clipPlane;
  51479. var invView = viewMatrix.clone();
  51480. invView.invert();
  51481. effect.setMatrix("invView", invView);
  51482. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51483. }
  51484. // VBOs
  51485. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51486. // Draw order
  51487. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51488. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51489. }
  51490. else {
  51491. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51492. }
  51493. if (this.forceDepthWrite) {
  51494. engine.setDepthWrite(true);
  51495. }
  51496. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51497. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51498. return this._particles.length;
  51499. };
  51500. /**
  51501. * Disposes the particle system and free the associated resources
  51502. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51503. */
  51504. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51505. if (disposeTexture === void 0) { disposeTexture = true; }
  51506. if (this._vertexBuffer) {
  51507. this._vertexBuffer.dispose();
  51508. this._vertexBuffer = null;
  51509. }
  51510. if (this._indexBuffer) {
  51511. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51512. this._indexBuffer = null;
  51513. }
  51514. if (disposeTexture && this.particleTexture) {
  51515. this.particleTexture.dispose();
  51516. this.particleTexture = null;
  51517. }
  51518. this._removeFromRoot();
  51519. // Remove from scene
  51520. var index = this._scene.particleSystems.indexOf(this);
  51521. if (index > -1) {
  51522. this._scene.particleSystems.splice(index, 1);
  51523. }
  51524. // Callback
  51525. this.onDisposeObservable.notifyObservers(this);
  51526. this.onDisposeObservable.clear();
  51527. };
  51528. /**
  51529. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51530. * @param radius The radius of the sphere to emit from
  51531. * @returns the emitter
  51532. */
  51533. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51534. if (radius === void 0) { radius = 1; }
  51535. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51536. this.particleEmitterType = particleEmitter;
  51537. return particleEmitter;
  51538. };
  51539. /**
  51540. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51541. * @param radius The radius of the sphere to emit from
  51542. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51543. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51544. * @returns the emitter
  51545. */
  51546. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51547. if (radius === void 0) { radius = 1; }
  51548. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51549. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51550. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51551. this.particleEmitterType = particleEmitter;
  51552. return particleEmitter;
  51553. };
  51554. /**
  51555. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51556. * @param radius The radius of the cone to emit from
  51557. * @param angle The base angle of the cone
  51558. * @returns the emitter
  51559. */
  51560. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51561. if (radius === void 0) { radius = 1; }
  51562. if (angle === void 0) { angle = Math.PI / 4; }
  51563. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51564. this.particleEmitterType = particleEmitter;
  51565. return particleEmitter;
  51566. };
  51567. // 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.
  51568. /**
  51569. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51570. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51571. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51572. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51573. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51574. * @returns the emitter
  51575. */
  51576. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51577. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51578. this.direction1 = direction1;
  51579. this.direction2 = direction2;
  51580. this.minEmitBox = minEmitBox;
  51581. this.maxEmitBox = maxEmitBox;
  51582. this.particleEmitterType = particleEmitter;
  51583. return particleEmitter;
  51584. };
  51585. // Clone
  51586. /**
  51587. * Clones the particle system.
  51588. * @param name The name of the cloned object
  51589. * @param newEmitter The new emitter to use
  51590. * @returns the cloned particle system
  51591. */
  51592. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51593. var custom = null;
  51594. var program = null;
  51595. if (this.customShader != null) {
  51596. program = this.customShader;
  51597. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51598. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51599. }
  51600. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51601. result.customShader = program;
  51602. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51603. if (newEmitter === undefined) {
  51604. newEmitter = this.emitter;
  51605. }
  51606. result.emitter = newEmitter;
  51607. if (this.particleTexture) {
  51608. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51609. }
  51610. if (!this.preventAutoStart) {
  51611. result.start();
  51612. }
  51613. return result;
  51614. };
  51615. /**
  51616. * Serializes the particle system to a JSON object.
  51617. * @returns the JSON object
  51618. */
  51619. ParticleSystem.prototype.serialize = function () {
  51620. var serializationObject = {};
  51621. serializationObject.name = this.name;
  51622. serializationObject.id = this.id;
  51623. // Emitter
  51624. if (this.emitter.position) {
  51625. var emitterMesh = this.emitter;
  51626. serializationObject.emitterId = emitterMesh.id;
  51627. }
  51628. else {
  51629. var emitterPosition = this.emitter;
  51630. serializationObject.emitter = emitterPosition.asArray();
  51631. }
  51632. serializationObject.capacity = this.getCapacity();
  51633. if (this.particleTexture) {
  51634. serializationObject.textureName = this.particleTexture.name;
  51635. }
  51636. // Animations
  51637. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51638. // Particle system
  51639. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51640. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51641. serializationObject.minSize = this.minSize;
  51642. serializationObject.maxSize = this.maxSize;
  51643. serializationObject.minEmitPower = this.minEmitPower;
  51644. serializationObject.maxEmitPower = this.maxEmitPower;
  51645. serializationObject.minLifeTime = this.minLifeTime;
  51646. serializationObject.maxLifeTime = this.maxLifeTime;
  51647. serializationObject.emitRate = this.emitRate;
  51648. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51649. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51650. serializationObject.gravity = this.gravity.asArray();
  51651. serializationObject.direction1 = this.direction1.asArray();
  51652. serializationObject.direction2 = this.direction2.asArray();
  51653. serializationObject.color1 = this.color1.asArray();
  51654. serializationObject.color2 = this.color2.asArray();
  51655. serializationObject.colorDead = this.colorDead.asArray();
  51656. serializationObject.updateSpeed = this.updateSpeed;
  51657. serializationObject.targetStopDuration = this.targetStopDuration;
  51658. serializationObject.textureMask = this.textureMask.asArray();
  51659. serializationObject.blendMode = this.blendMode;
  51660. serializationObject.customShader = this.customShader;
  51661. serializationObject.preventAutoStart = this.preventAutoStart;
  51662. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51663. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51664. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51665. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51666. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51667. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51668. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51669. // Emitter
  51670. if (this.particleEmitterType) {
  51671. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51672. }
  51673. return serializationObject;
  51674. };
  51675. /**
  51676. * Parses a JSON object to create a particle system.
  51677. * @param parsedParticleSystem The JSON object to parse
  51678. * @param scene The scene to create the particle system in
  51679. * @param rootUrl The root url to use to load external dependencies like texture
  51680. * @returns the Parsed particle system
  51681. */
  51682. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51683. var name = parsedParticleSystem.name;
  51684. var custom = null;
  51685. var program = null;
  51686. if (parsedParticleSystem.customShader) {
  51687. program = parsedParticleSystem.customShader;
  51688. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51689. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51690. }
  51691. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51692. particleSystem.customShader = program;
  51693. if (parsedParticleSystem.id) {
  51694. particleSystem.id = parsedParticleSystem.id;
  51695. }
  51696. // Auto start
  51697. if (parsedParticleSystem.preventAutoStart) {
  51698. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51699. }
  51700. // Texture
  51701. if (parsedParticleSystem.textureName) {
  51702. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51703. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51704. }
  51705. // Emitter
  51706. if (parsedParticleSystem.emitterId) {
  51707. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51708. }
  51709. else {
  51710. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51711. }
  51712. // Animations
  51713. if (parsedParticleSystem.animations) {
  51714. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51715. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51716. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51717. }
  51718. }
  51719. if (parsedParticleSystem.autoAnimate) {
  51720. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51721. }
  51722. // Particle system
  51723. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51724. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51725. particleSystem.minSize = parsedParticleSystem.minSize;
  51726. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51727. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51728. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51729. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51730. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51731. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51732. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51733. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51734. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51735. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51736. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51737. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51738. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51739. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51740. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51741. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51742. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51743. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51744. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51745. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51746. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51747. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51748. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51749. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51750. if (!particleSystem.preventAutoStart) {
  51751. particleSystem.start();
  51752. }
  51753. return particleSystem;
  51754. };
  51755. /**
  51756. * Source color is added to the destination color without alpha affecting the result.
  51757. */
  51758. ParticleSystem.BLENDMODE_ONEONE = 0;
  51759. /**
  51760. * Blend current color and particle color using particle’s alpha.
  51761. */
  51762. ParticleSystem.BLENDMODE_STANDARD = 1;
  51763. return ParticleSystem;
  51764. }());
  51765. BABYLON.ParticleSystem = ParticleSystem;
  51766. })(BABYLON || (BABYLON = {}));
  51767. //# sourceMappingURL=babylon.particleSystem.js.map
  51768. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51769. var BABYLON;
  51770. (function (BABYLON) {
  51771. /**
  51772. * Particle emitter emitting particles from the inside of a box.
  51773. * It emits the particles randomly between 2 given directions.
  51774. */
  51775. var BoxParticleEmitter = /** @class */ (function () {
  51776. /**
  51777. * Creates a new instance of @see BoxParticleEmitter
  51778. */
  51779. function BoxParticleEmitter() {
  51780. /**
  51781. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51782. */
  51783. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51784. /**
  51785. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51786. */
  51787. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51788. /**
  51789. * 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.
  51790. */
  51791. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51792. /**
  51793. * 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.
  51794. */
  51795. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51796. }
  51797. /**
  51798. * Called by the particle System when the direction is computed for the created particle.
  51799. * @param emitPower is the power of the particle (speed)
  51800. * @param worldMatrix is the world matrix of the particle system
  51801. * @param directionToUpdate is the direction vector to update with the result
  51802. * @param particle is the particle we are computed the direction for
  51803. */
  51804. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51805. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51806. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51807. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51808. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51809. };
  51810. /**
  51811. * Called by the particle System when the position is computed for the created particle.
  51812. * @param worldMatrix is the world matrix of the particle system
  51813. * @param positionToUpdate is the position vector to update with the result
  51814. * @param particle is the particle we are computed the position for
  51815. */
  51816. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51817. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51818. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51819. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51820. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51821. };
  51822. /**
  51823. * Clones the current emitter and returns a copy of it
  51824. * @returns the new emitter
  51825. */
  51826. BoxParticleEmitter.prototype.clone = function () {
  51827. var newOne = new BoxParticleEmitter();
  51828. BABYLON.Tools.DeepCopy(this, newOne);
  51829. return newOne;
  51830. };
  51831. /**
  51832. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51833. * @param effect defines the update shader
  51834. */
  51835. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51836. effect.setVector3("direction1", this.direction1);
  51837. effect.setVector3("direction2", this.direction2);
  51838. effect.setVector3("minEmitBox", this.minEmitBox);
  51839. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51840. };
  51841. /**
  51842. * Returns a string to use to update the GPU particles update shader
  51843. * @returns a string containng the defines string
  51844. */
  51845. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51846. return "#define BOXEMITTER";
  51847. };
  51848. /**
  51849. * Returns the string "BoxEmitter"
  51850. * @returns a string containing the class name
  51851. */
  51852. BoxParticleEmitter.prototype.getClassName = function () {
  51853. return "BoxEmitter";
  51854. };
  51855. /**
  51856. * Serializes the particle system to a JSON object.
  51857. * @returns the JSON object
  51858. */
  51859. BoxParticleEmitter.prototype.serialize = function () {
  51860. var serializationObject = {};
  51861. serializationObject.type = this.getClassName();
  51862. serializationObject.direction1 = this.direction1.asArray();
  51863. ;
  51864. serializationObject.direction2 = this.direction2.asArray();
  51865. ;
  51866. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51867. ;
  51868. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51869. ;
  51870. return serializationObject;
  51871. };
  51872. /**
  51873. * Parse properties from a JSON object
  51874. * @param serializationObject defines the JSON object
  51875. */
  51876. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51877. this.direction1.copyFrom(serializationObject.direction1);
  51878. this.direction2.copyFrom(serializationObject.direction2);
  51879. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51880. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51881. };
  51882. return BoxParticleEmitter;
  51883. }());
  51884. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51885. })(BABYLON || (BABYLON = {}));
  51886. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51887. var BABYLON;
  51888. (function (BABYLON) {
  51889. /**
  51890. * Particle emitter emitting particles from the inside of a cone.
  51891. * It emits the particles alongside the cone volume from the base to the particle.
  51892. * The emission direction might be randomized.
  51893. */
  51894. var ConeParticleEmitter = /** @class */ (function () {
  51895. /**
  51896. * Creates a new instance of @see ConeParticleEmitter
  51897. * @param radius the radius of the emission cone (1 by default)
  51898. * @param angles the cone base angle (PI by default)
  51899. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51900. */
  51901. function ConeParticleEmitter(radius,
  51902. /**
  51903. * The radius of the emission cone.
  51904. */
  51905. angle,
  51906. /**
  51907. * The cone base angle.
  51908. */
  51909. directionRandomizer) {
  51910. if (radius === void 0) { radius = 1; }
  51911. if (angle === void 0) { angle = Math.PI; }
  51912. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51913. this.angle = angle;
  51914. this.directionRandomizer = directionRandomizer;
  51915. this.radius = radius;
  51916. }
  51917. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51918. /**
  51919. * Gets the radius of the emission cone.
  51920. */
  51921. get: function () {
  51922. return this._radius;
  51923. },
  51924. /**
  51925. * Sets the radius of the emission cone.
  51926. */
  51927. set: function (value) {
  51928. this._radius = value;
  51929. if (this.angle !== 0) {
  51930. this._height = value / Math.tan(this.angle / 2);
  51931. }
  51932. else {
  51933. this._height = 1;
  51934. }
  51935. },
  51936. enumerable: true,
  51937. configurable: true
  51938. });
  51939. /**
  51940. * Called by the particle System when the direction is computed for the created particle.
  51941. * @param emitPower is the power of the particle (speed)
  51942. * @param worldMatrix is the world matrix of the particle system
  51943. * @param directionToUpdate is the direction vector to update with the result
  51944. * @param particle is the particle we are computed the direction for
  51945. */
  51946. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51947. if (this.angle === 0) {
  51948. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51949. }
  51950. else {
  51951. // measure the direction Vector from the emitter to the particle.
  51952. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51953. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51954. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51955. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51956. direction.x += randX;
  51957. direction.y += randY;
  51958. direction.z += randZ;
  51959. direction.normalize();
  51960. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51961. }
  51962. };
  51963. /**
  51964. * Called by the particle System when the position is computed for the created particle.
  51965. * @param worldMatrix is the world matrix of the particle system
  51966. * @param positionToUpdate is the position vector to update with the result
  51967. * @param particle is the particle we are computed the position for
  51968. */
  51969. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51970. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51971. var h = BABYLON.Scalar.RandomRange(0, 1);
  51972. // Better distribution in a cone at normal angles.
  51973. h = 1 - h * h;
  51974. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51975. radius = radius * h / this._height;
  51976. var randX = radius * Math.sin(s);
  51977. var randZ = radius * Math.cos(s);
  51978. var randY = h * this._height;
  51979. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51980. };
  51981. /**
  51982. * Clones the current emitter and returns a copy of it
  51983. * @returns the new emitter
  51984. */
  51985. ConeParticleEmitter.prototype.clone = function () {
  51986. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51987. BABYLON.Tools.DeepCopy(this, newOne);
  51988. return newOne;
  51989. };
  51990. /**
  51991. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51992. * @param effect defines the update shader
  51993. */
  51994. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51995. effect.setFloat("radius", this.radius);
  51996. effect.setFloat("angle", this.angle);
  51997. effect.setFloat("height", this._height);
  51998. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51999. };
  52000. /**
  52001. * Returns a string to use to update the GPU particles update shader
  52002. * @returns a string containng the defines string
  52003. */
  52004. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52005. return "#define CONEEMITTER";
  52006. };
  52007. /**
  52008. * Returns the string "BoxEmitter"
  52009. * @returns a string containing the class name
  52010. */
  52011. ConeParticleEmitter.prototype.getClassName = function () {
  52012. return "ConeEmitter";
  52013. };
  52014. /**
  52015. * Serializes the particle system to a JSON object.
  52016. * @returns the JSON object
  52017. */
  52018. ConeParticleEmitter.prototype.serialize = function () {
  52019. var serializationObject = {};
  52020. serializationObject.type = this.getClassName();
  52021. serializationObject.radius = this.radius;
  52022. serializationObject.angle = this.angle;
  52023. serializationObject.directionRandomizer = this.directionRandomizer;
  52024. return serializationObject;
  52025. };
  52026. /**
  52027. * Parse properties from a JSON object
  52028. * @param serializationObject defines the JSON object
  52029. */
  52030. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52031. this.radius = serializationObject.radius;
  52032. this.angle = serializationObject.angle;
  52033. this.directionRandomizer = serializationObject.directionRandomizer;
  52034. };
  52035. return ConeParticleEmitter;
  52036. }());
  52037. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52038. })(BABYLON || (BABYLON = {}));
  52039. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52040. var BABYLON;
  52041. (function (BABYLON) {
  52042. /**
  52043. * Particle emitter emitting particles from the inside of a sphere.
  52044. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52045. */
  52046. var SphereParticleEmitter = /** @class */ (function () {
  52047. /**
  52048. * Creates a new instance of @see SphereParticleEmitter
  52049. * @param radius the radius of the emission sphere (1 by default)
  52050. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52051. */
  52052. function SphereParticleEmitter(
  52053. /**
  52054. * The radius of the emission sphere.
  52055. */
  52056. radius,
  52057. /**
  52058. * How much to randomize the particle direction [0-1].
  52059. */
  52060. directionRandomizer) {
  52061. if (radius === void 0) { radius = 1; }
  52062. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52063. this.radius = radius;
  52064. this.directionRandomizer = directionRandomizer;
  52065. }
  52066. /**
  52067. * Called by the particle System when the direction is computed for the created particle.
  52068. * @param emitPower is the power of the particle (speed)
  52069. * @param worldMatrix is the world matrix of the particle system
  52070. * @param directionToUpdate is the direction vector to update with the result
  52071. * @param particle is the particle we are computed the direction for
  52072. */
  52073. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52074. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52075. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52076. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52077. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52078. direction.x += randX;
  52079. direction.y += randY;
  52080. direction.z += randZ;
  52081. direction.normalize();
  52082. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52083. };
  52084. /**
  52085. * Called by the particle System when the position is computed for the created particle.
  52086. * @param worldMatrix is the world matrix of the particle system
  52087. * @param positionToUpdate is the position vector to update with the result
  52088. * @param particle is the particle we are computed the position for
  52089. */
  52090. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52091. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52092. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52093. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52094. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52095. var randY = randRadius * Math.cos(theta);
  52096. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52097. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52098. };
  52099. /**
  52100. * Clones the current emitter and returns a copy of it
  52101. * @returns the new emitter
  52102. */
  52103. SphereParticleEmitter.prototype.clone = function () {
  52104. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52105. BABYLON.Tools.DeepCopy(this, newOne);
  52106. return newOne;
  52107. };
  52108. /**
  52109. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52110. * @param effect defines the update shader
  52111. */
  52112. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52113. effect.setFloat("radius", this.radius);
  52114. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52115. };
  52116. /**
  52117. * Returns a string to use to update the GPU particles update shader
  52118. * @returns a string containng the defines string
  52119. */
  52120. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52121. return "#define SPHEREEMITTER";
  52122. };
  52123. /**
  52124. * Returns the string "SphereParticleEmitter"
  52125. * @returns a string containing the class name
  52126. */
  52127. SphereParticleEmitter.prototype.getClassName = function () {
  52128. return "SphereParticleEmitter";
  52129. };
  52130. /**
  52131. * Serializes the particle system to a JSON object.
  52132. * @returns the JSON object
  52133. */
  52134. SphereParticleEmitter.prototype.serialize = function () {
  52135. var serializationObject = {};
  52136. serializationObject.type = this.getClassName();
  52137. serializationObject.radius = this.radius;
  52138. serializationObject.directionRandomizer = this.directionRandomizer;
  52139. return serializationObject;
  52140. };
  52141. /**
  52142. * Parse properties from a JSON object
  52143. * @param serializationObject defines the JSON object
  52144. */
  52145. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52146. this.radius = serializationObject.radius;
  52147. this.directionRandomizer = serializationObject.directionRandomizer;
  52148. };
  52149. return SphereParticleEmitter;
  52150. }());
  52151. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52152. /**
  52153. * Particle emitter emitting particles from the inside of a sphere.
  52154. * It emits the particles randomly between two vectors.
  52155. */
  52156. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52157. __extends(SphereDirectedParticleEmitter, _super);
  52158. /**
  52159. * Creates a new instance of @see SphereDirectedParticleEmitter
  52160. * @param radius the radius of the emission sphere (1 by default)
  52161. * @param direction1 the min limit of the emission direction (up vector by default)
  52162. * @param direction2 the max limit of the emission direction (up vector by default)
  52163. */
  52164. function SphereDirectedParticleEmitter(radius,
  52165. /**
  52166. * The min limit of the emission direction.
  52167. */
  52168. direction1,
  52169. /**
  52170. * The max limit of the emission direction.
  52171. */
  52172. direction2) {
  52173. if (radius === void 0) { radius = 1; }
  52174. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52175. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52176. var _this = _super.call(this, radius) || this;
  52177. _this.direction1 = direction1;
  52178. _this.direction2 = direction2;
  52179. return _this;
  52180. }
  52181. /**
  52182. * Called by the particle System when the direction is computed for the created particle.
  52183. * @param emitPower is the power of the particle (speed)
  52184. * @param worldMatrix is the world matrix of the particle system
  52185. * @param directionToUpdate is the direction vector to update with the result
  52186. * @param particle is the particle we are computed the direction for
  52187. */
  52188. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52189. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52190. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52191. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52192. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52193. };
  52194. /**
  52195. * Clones the current emitter and returns a copy of it
  52196. * @returns the new emitter
  52197. */
  52198. SphereDirectedParticleEmitter.prototype.clone = function () {
  52199. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52200. BABYLON.Tools.DeepCopy(this, newOne);
  52201. return newOne;
  52202. };
  52203. /**
  52204. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52205. * @param effect defines the update shader
  52206. */
  52207. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52208. effect.setFloat("radius", this.radius);
  52209. effect.setVector3("direction1", this.direction1);
  52210. effect.setVector3("direction2", this.direction2);
  52211. };
  52212. /**
  52213. * Returns a string to use to update the GPU particles update shader
  52214. * @returns a string containng the defines string
  52215. */
  52216. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52217. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52218. };
  52219. /**
  52220. * Returns the string "SphereDirectedParticleEmitter"
  52221. * @returns a string containing the class name
  52222. */
  52223. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52224. return "SphereDirectedParticleEmitter";
  52225. };
  52226. /**
  52227. * Serializes the particle system to a JSON object.
  52228. * @returns the JSON object
  52229. */
  52230. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52231. var serializationObject = _super.prototype.serialize.call(this);
  52232. ;
  52233. serializationObject.direction1 = this.direction1.asArray();
  52234. ;
  52235. serializationObject.direction2 = this.direction2.asArray();
  52236. ;
  52237. return serializationObject;
  52238. };
  52239. /**
  52240. * Parse properties from a JSON object
  52241. * @param serializationObject defines the JSON object
  52242. */
  52243. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52244. _super.prototype.parse.call(this, serializationObject);
  52245. this.direction1.copyFrom(serializationObject.direction1);
  52246. this.direction2.copyFrom(serializationObject.direction2);
  52247. };
  52248. return SphereDirectedParticleEmitter;
  52249. }(SphereParticleEmitter));
  52250. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52251. })(BABYLON || (BABYLON = {}));
  52252. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52253. var BABYLON;
  52254. (function (BABYLON) {
  52255. /**
  52256. * Represents one particle of a solid particle system.
  52257. * @see SolidParticleSystem
  52258. */
  52259. var SolidParticle = /** @class */ (function () {
  52260. /**
  52261. * Creates a Solid Particle object.
  52262. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52263. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52264. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52265. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52266. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52267. * @param shapeId (integer) is the model shape identifier in the SPS.
  52268. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52269. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52270. */
  52271. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52272. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52273. /**
  52274. * particle global index
  52275. */
  52276. this.idx = 0;
  52277. /**
  52278. * The color of the particle
  52279. */
  52280. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52281. /**
  52282. * The world space position of the particle.
  52283. */
  52284. this.position = BABYLON.Vector3.Zero();
  52285. /**
  52286. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52287. */
  52288. this.rotation = BABYLON.Vector3.Zero();
  52289. /**
  52290. * The scaling of the particle.
  52291. */
  52292. this.scaling = BABYLON.Vector3.One();
  52293. /**
  52294. * The uvs of the particle.
  52295. */
  52296. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52297. /**
  52298. * The current speed of the particle.
  52299. */
  52300. this.velocity = BABYLON.Vector3.Zero();
  52301. /**
  52302. * The pivot point in the particle local space.
  52303. */
  52304. this.pivot = BABYLON.Vector3.Zero();
  52305. /**
  52306. * Must the particle be translated from its pivot point in its local space ?
  52307. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52308. * Default : false
  52309. */
  52310. this.translateFromPivot = false;
  52311. /**
  52312. * Is the particle active or not ?
  52313. */
  52314. this.alive = true;
  52315. /**
  52316. * Is the particle visible or not ?
  52317. */
  52318. this.isVisible = true;
  52319. /**
  52320. * Index of this particle in the global "positions" array (Internal use)
  52321. */
  52322. this._pos = 0;
  52323. /**
  52324. * Index of this particle in the global "indices" array (Internal use)
  52325. */
  52326. this._ind = 0;
  52327. /**
  52328. * ModelShape id of this particle
  52329. */
  52330. this.shapeId = 0;
  52331. /**
  52332. * Index of the particle in its shape id (Internal use)
  52333. */
  52334. this.idxInShape = 0;
  52335. /**
  52336. * Still set as invisible in order to skip useless computations (Internal use)
  52337. */
  52338. this._stillInvisible = false;
  52339. /**
  52340. * Last computed particle rotation matrix
  52341. */
  52342. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  52343. /**
  52344. * Parent particle Id, if any.
  52345. * Default null.
  52346. */
  52347. this.parentId = null;
  52348. /**
  52349. * Internal global position in the SPS.
  52350. */
  52351. this._globalPosition = BABYLON.Vector3.Zero();
  52352. this.idx = particleIndex;
  52353. this._pos = positionIndex;
  52354. this._ind = indiceIndex;
  52355. this._model = model;
  52356. this.shapeId = shapeId;
  52357. this.idxInShape = idxInShape;
  52358. this._sps = sps;
  52359. if (modelBoundingInfo) {
  52360. this._modelBoundingInfo = modelBoundingInfo;
  52361. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52362. }
  52363. }
  52364. Object.defineProperty(SolidParticle.prototype, "scale", {
  52365. /**
  52366. * Legacy support, changed scale to scaling
  52367. */
  52368. get: function () {
  52369. return this.scaling;
  52370. },
  52371. /**
  52372. * Legacy support, changed scale to scaling
  52373. */
  52374. set: function (scale) {
  52375. this.scaling = scale;
  52376. },
  52377. enumerable: true,
  52378. configurable: true
  52379. });
  52380. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52381. /**
  52382. * Legacy support, changed quaternion to rotationQuaternion
  52383. */
  52384. get: function () {
  52385. return this.rotationQuaternion;
  52386. },
  52387. /**
  52388. * Legacy support, changed quaternion to rotationQuaternion
  52389. */
  52390. set: function (q) {
  52391. this.rotationQuaternion = q;
  52392. },
  52393. enumerable: true,
  52394. configurable: true
  52395. });
  52396. /**
  52397. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52398. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52399. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  52400. * @returns true if it intersects
  52401. */
  52402. SolidParticle.prototype.intersectsMesh = function (target) {
  52403. if (!this._boundingInfo || !target._boundingInfo) {
  52404. return false;
  52405. }
  52406. if (this._sps._bSphereOnly) {
  52407. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52408. }
  52409. return this._boundingInfo.intersects(target._boundingInfo, false);
  52410. };
  52411. return SolidParticle;
  52412. }());
  52413. BABYLON.SolidParticle = SolidParticle;
  52414. /**
  52415. * Represents the shape of the model used by one particle of a solid particle system.
  52416. * SPS internal tool, don't use it manually.
  52417. * @see SolidParticleSystem
  52418. */
  52419. var ModelShape = /** @class */ (function () {
  52420. /**
  52421. * 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.
  52422. * SPS internal tool, don't use it manually.
  52423. * @ignore
  52424. */
  52425. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  52426. /**
  52427. * length of the shape in the model indices array (internal use)
  52428. */
  52429. this._indicesLength = 0;
  52430. this.shapeID = id;
  52431. this._shape = shape;
  52432. this._indicesLength = indicesLength;
  52433. this._shapeUV = shapeUV;
  52434. this._positionFunction = posFunction;
  52435. this._vertexFunction = vtxFunction;
  52436. }
  52437. return ModelShape;
  52438. }());
  52439. BABYLON.ModelShape = ModelShape;
  52440. /**
  52441. * Represents a Depth Sorted Particle in the solid particle system.
  52442. * @see SolidParticleSystem
  52443. */
  52444. var DepthSortedParticle = /** @class */ (function () {
  52445. function DepthSortedParticle() {
  52446. /**
  52447. * Index of the particle in the "indices" array
  52448. */
  52449. this.ind = 0;
  52450. /**
  52451. * Length of the particle shape in the "indices" array
  52452. */
  52453. this.indicesLength = 0;
  52454. /**
  52455. * Squared distance from the particle to the camera
  52456. */
  52457. this.sqDistance = 0.0;
  52458. }
  52459. return DepthSortedParticle;
  52460. }());
  52461. BABYLON.DepthSortedParticle = DepthSortedParticle;
  52462. })(BABYLON || (BABYLON = {}));
  52463. //# sourceMappingURL=babylon.solidParticle.js.map
  52464. var BABYLON;
  52465. (function (BABYLON) {
  52466. /**
  52467. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  52468. *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.
  52469. * The SPS is also a particle system. It provides some methods to manage the particles.
  52470. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  52471. *
  52472. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52473. */
  52474. var SolidParticleSystem = /** @class */ (function () {
  52475. /**
  52476. * Creates a SPS (Solid Particle System) object.
  52477. * @param name (String) is the SPS name, this will be the underlying mesh name.
  52478. * @param scene (Scene) is the scene in which the SPS is added.
  52479. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  52480. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  52481. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  52482. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  52483. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52484. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52485. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52486. */
  52487. function SolidParticleSystem(name, scene, options) {
  52488. /**
  52489. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52490. * Example : var p = SPS.particles[i];
  52491. */
  52492. this.particles = new Array();
  52493. /**
  52494. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52495. */
  52496. this.nbParticles = 0;
  52497. /**
  52498. * If the particles must ever face the camera (default false). Useful for planar particles.
  52499. */
  52500. this.billboard = false;
  52501. /**
  52502. * Recompute normals when adding a shape
  52503. */
  52504. this.recomputeNormals = true;
  52505. /**
  52506. * This a counter ofr your own usage. It's not set by any SPS functions.
  52507. */
  52508. this.counter = 0;
  52509. /**
  52510. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52511. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52512. */
  52513. this.vars = {};
  52514. /**
  52515. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  52516. */
  52517. this._bSphereOnly = false;
  52518. /**
  52519. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  52520. */
  52521. this._bSphereRadiusFactor = 1.0;
  52522. this._positions = new Array();
  52523. this._indices = new Array();
  52524. this._normals = new Array();
  52525. this._colors = new Array();
  52526. this._uvs = new Array();
  52527. this._index = 0; // indices index
  52528. this._updatable = true;
  52529. this._pickable = false;
  52530. this._isVisibilityBoxLocked = false;
  52531. this._alwaysVisible = false;
  52532. this._depthSort = false;
  52533. this._shapeCounter = 0;
  52534. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  52535. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52536. this._computeParticleColor = true;
  52537. this._computeParticleTexture = true;
  52538. this._computeParticleRotation = true;
  52539. this._computeParticleVertex = false;
  52540. this._computeBoundingBox = false;
  52541. this._depthSortParticles = true;
  52542. this._cam_axisZ = BABYLON.Vector3.Zero();
  52543. this._cam_axisY = BABYLON.Vector3.Zero();
  52544. this._cam_axisX = BABYLON.Vector3.Zero();
  52545. this._axisZ = BABYLON.Axis.Z;
  52546. this._camDir = BABYLON.Vector3.Zero();
  52547. this._camInvertedPosition = BABYLON.Vector3.Zero();
  52548. this._rotMatrix = new BABYLON.Matrix();
  52549. this._invertMatrix = new BABYLON.Matrix();
  52550. this._rotated = BABYLON.Vector3.Zero();
  52551. this._quaternion = new BABYLON.Quaternion();
  52552. this._vertex = BABYLON.Vector3.Zero();
  52553. this._normal = BABYLON.Vector3.Zero();
  52554. this._yaw = 0.0;
  52555. this._pitch = 0.0;
  52556. this._roll = 0.0;
  52557. this._halfroll = 0.0;
  52558. this._halfpitch = 0.0;
  52559. this._halfyaw = 0.0;
  52560. this._sinRoll = 0.0;
  52561. this._cosRoll = 0.0;
  52562. this._sinPitch = 0.0;
  52563. this._cosPitch = 0.0;
  52564. this._sinYaw = 0.0;
  52565. this._cosYaw = 0.0;
  52566. this._mustUnrotateFixedNormals = false;
  52567. this._minimum = BABYLON.Vector3.Zero();
  52568. this._maximum = BABYLON.Vector3.Zero();
  52569. this._minBbox = BABYLON.Vector3.Zero();
  52570. this._maxBbox = BABYLON.Vector3.Zero();
  52571. this._particlesIntersect = false;
  52572. this._depthSortFunction = function (p1, p2) {
  52573. return (p2.sqDistance - p1.sqDistance);
  52574. };
  52575. this._needs32Bits = false;
  52576. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  52577. this._scaledPivot = BABYLON.Vector3.Zero();
  52578. this._particleHasParent = false;
  52579. this.name = name;
  52580. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52581. this._camera = scene.activeCamera;
  52582. this._pickable = options ? options.isPickable : false;
  52583. this._depthSort = options ? options.enableDepthSort : false;
  52584. this._particlesIntersect = options ? options.particleIntersection : false;
  52585. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52586. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52587. if (options && options.updatable) {
  52588. this._updatable = options.updatable;
  52589. }
  52590. else {
  52591. this._updatable = true;
  52592. }
  52593. if (this._pickable) {
  52594. this.pickedParticles = [];
  52595. }
  52596. if (this._depthSort) {
  52597. this.depthSortedParticles = [];
  52598. }
  52599. }
  52600. /**
  52601. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52602. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52603. * @returns the created mesh
  52604. */
  52605. SolidParticleSystem.prototype.buildMesh = function () {
  52606. if (this.nbParticles === 0) {
  52607. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52608. this.addShape(triangle, 1);
  52609. triangle.dispose();
  52610. }
  52611. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  52612. this._positions32 = new Float32Array(this._positions);
  52613. this._uvs32 = new Float32Array(this._uvs);
  52614. this._colors32 = new Float32Array(this._colors);
  52615. if (this.recomputeNormals) {
  52616. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  52617. }
  52618. this._normals32 = new Float32Array(this._normals);
  52619. this._fixedNormal32 = new Float32Array(this._normals);
  52620. if (this._mustUnrotateFixedNormals) {
  52621. this._unrotateFixedNormals();
  52622. }
  52623. var vertexData = new BABYLON.VertexData();
  52624. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  52625. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52626. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52627. if (this._uvs32) {
  52628. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52629. ;
  52630. }
  52631. if (this._colors32) {
  52632. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52633. }
  52634. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52635. vertexData.applyToMesh(mesh, this._updatable);
  52636. this.mesh = mesh;
  52637. this.mesh.isPickable = this._pickable;
  52638. // free memory
  52639. if (!this._depthSort) {
  52640. this._indices = null;
  52641. }
  52642. this._positions = null;
  52643. this._normals = null;
  52644. this._uvs = null;
  52645. this._colors = null;
  52646. if (!this._updatable) {
  52647. this.particles.length = 0;
  52648. }
  52649. return mesh;
  52650. };
  52651. /**
  52652. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52653. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  52654. * Thus the particles generated from `digest()` have their property `position` set yet.
  52655. * @param mesh ( Mesh ) is the mesh to be digested
  52656. * @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
  52657. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  52658. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  52659. * @returns the current SPS
  52660. */
  52661. SolidParticleSystem.prototype.digest = function (mesh, options) {
  52662. var size = (options && options.facetNb) || 1;
  52663. var number = (options && options.number) || 0;
  52664. var delta = (options && options.delta) || 0;
  52665. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52666. var meshInd = mesh.getIndices();
  52667. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52668. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52669. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52670. var f = 0; // facet counter
  52671. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  52672. // compute size from number
  52673. if (number) {
  52674. number = (number > totalFacets) ? totalFacets : number;
  52675. size = Math.round(totalFacets / number);
  52676. delta = 0;
  52677. }
  52678. else {
  52679. size = (size > totalFacets) ? totalFacets : size;
  52680. }
  52681. var facetPos = []; // submesh positions
  52682. var facetInd = []; // submesh indices
  52683. var facetUV = []; // submesh UV
  52684. var facetCol = []; // submesh colors
  52685. var barycenter = BABYLON.Vector3.Zero();
  52686. var sizeO = size;
  52687. while (f < totalFacets) {
  52688. size = sizeO + Math.floor((1 + delta) * Math.random());
  52689. if (f > totalFacets - size) {
  52690. size = totalFacets - f;
  52691. }
  52692. // reset temp arrays
  52693. facetPos.length = 0;
  52694. facetInd.length = 0;
  52695. facetUV.length = 0;
  52696. facetCol.length = 0;
  52697. // iterate over "size" facets
  52698. var fi = 0;
  52699. for (var j = f * 3; j < (f + size) * 3; j++) {
  52700. facetInd.push(fi);
  52701. var i = meshInd[j];
  52702. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  52703. if (meshUV) {
  52704. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  52705. }
  52706. if (meshCol) {
  52707. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  52708. }
  52709. fi++;
  52710. }
  52711. // create a model shape for each single particle
  52712. var idx = this.nbParticles;
  52713. var shape = this._posToShape(facetPos);
  52714. var shapeUV = this._uvsToShapeUV(facetUV);
  52715. // compute the barycenter of the shape
  52716. var v;
  52717. for (v = 0; v < shape.length; v++) {
  52718. barycenter.addInPlace(shape[v]);
  52719. }
  52720. barycenter.scaleInPlace(1 / shape.length);
  52721. // shift the shape from its barycenter to the origin
  52722. for (v = 0; v < shape.length; v++) {
  52723. shape[v].subtractInPlace(barycenter);
  52724. }
  52725. var bInfo;
  52726. if (this._particlesIntersect) {
  52727. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  52728. }
  52729. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  52730. // add the particle in the SPS
  52731. var currentPos = this._positions.length;
  52732. var currentInd = this._indices.length;
  52733. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  52734. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  52735. // initialize the particle position
  52736. this.particles[this.nbParticles].position.addInPlace(barycenter);
  52737. this._index += shape.length;
  52738. idx++;
  52739. this.nbParticles++;
  52740. this._shapeCounter++;
  52741. f += size;
  52742. }
  52743. return this;
  52744. };
  52745. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  52746. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  52747. var index = 0;
  52748. var idx = 0;
  52749. for (var p = 0; p < this.particles.length; p++) {
  52750. this._particle = this.particles[p];
  52751. this._shape = this._particle._model._shape;
  52752. if (this._particle.rotationQuaternion) {
  52753. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52754. }
  52755. else {
  52756. this._yaw = this._particle.rotation.y;
  52757. this._pitch = this._particle.rotation.x;
  52758. this._roll = this._particle.rotation.z;
  52759. this._quaternionRotationYPR();
  52760. }
  52761. this._quaternionToRotationMatrix();
  52762. this._rotMatrix.invertToRef(this._invertMatrix);
  52763. for (var pt = 0; pt < this._shape.length; pt++) {
  52764. idx = index + pt * 3;
  52765. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  52766. this._fixedNormal32[idx] = this._normal.x;
  52767. this._fixedNormal32[idx + 1] = this._normal.y;
  52768. this._fixedNormal32[idx + 2] = this._normal.z;
  52769. }
  52770. index = idx + 3;
  52771. }
  52772. };
  52773. //reset copy
  52774. SolidParticleSystem.prototype._resetCopy = function () {
  52775. this._copy.position.x = 0;
  52776. this._copy.position.y = 0;
  52777. this._copy.position.z = 0;
  52778. this._copy.rotation.x = 0;
  52779. this._copy.rotation.y = 0;
  52780. this._copy.rotation.z = 0;
  52781. this._copy.rotationQuaternion = null;
  52782. this._copy.scaling.x = 1.0;
  52783. this._copy.scaling.y = 1.0;
  52784. this._copy.scaling.z = 1.0;
  52785. this._copy.uvs.x = 0;
  52786. this._copy.uvs.y = 0;
  52787. this._copy.uvs.z = 1.0;
  52788. this._copy.uvs.w = 1.0;
  52789. this._copy.color = null;
  52790. this._copy.translateFromPivot = false;
  52791. };
  52792. // _meshBuilder : inserts the shape model in the global SPS mesh
  52793. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  52794. var i;
  52795. var u = 0;
  52796. var c = 0;
  52797. var n = 0;
  52798. this._resetCopy();
  52799. if (options && options.positionFunction) {
  52800. options.positionFunction(this._copy, idx, idxInShape);
  52801. this._mustUnrotateFixedNormals = true;
  52802. }
  52803. if (this._copy.rotationQuaternion) {
  52804. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52805. }
  52806. else {
  52807. this._yaw = this._copy.rotation.y;
  52808. this._pitch = this._copy.rotation.x;
  52809. this._roll = this._copy.rotation.z;
  52810. this._quaternionRotationYPR();
  52811. }
  52812. this._quaternionToRotationMatrix();
  52813. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  52814. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  52815. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  52816. if (this._copy.translateFromPivot) {
  52817. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52818. }
  52819. else {
  52820. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52821. }
  52822. for (i = 0; i < shape.length; i++) {
  52823. this._vertex.x = shape[i].x;
  52824. this._vertex.y = shape[i].y;
  52825. this._vertex.z = shape[i].z;
  52826. if (options && options.vertexFunction) {
  52827. options.vertexFunction(this._copy, this._vertex, i);
  52828. }
  52829. this._vertex.x *= this._copy.scaling.x;
  52830. this._vertex.y *= this._copy.scaling.y;
  52831. this._vertex.z *= this._copy.scaling.z;
  52832. this._vertex.x -= this._scaledPivot.x;
  52833. this._vertex.y -= this._scaledPivot.y;
  52834. this._vertex.z -= this._scaledPivot.z;
  52835. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52836. this._rotated.addInPlace(this._pivotBackTranslation);
  52837. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  52838. if (meshUV) {
  52839. 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);
  52840. u += 2;
  52841. }
  52842. if (this._copy.color) {
  52843. this._color = this._copy.color;
  52844. }
  52845. else if (meshCol && meshCol[c] !== undefined) {
  52846. this._color.r = meshCol[c];
  52847. this._color.g = meshCol[c + 1];
  52848. this._color.b = meshCol[c + 2];
  52849. this._color.a = meshCol[c + 3];
  52850. }
  52851. else {
  52852. this._color.r = 1.0;
  52853. this._color.g = 1.0;
  52854. this._color.b = 1.0;
  52855. this._color.a = 1.0;
  52856. }
  52857. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  52858. c += 4;
  52859. if (!this.recomputeNormals && meshNor) {
  52860. this._normal.x = meshNor[n];
  52861. this._normal.y = meshNor[n + 1];
  52862. this._normal.z = meshNor[n + 2];
  52863. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  52864. normals.push(this._normal.x, this._normal.y, this._normal.z);
  52865. n += 3;
  52866. }
  52867. }
  52868. for (i = 0; i < meshInd.length; i++) {
  52869. var current_ind = p + meshInd[i];
  52870. indices.push(current_ind);
  52871. if (current_ind > 65535) {
  52872. this._needs32Bits = true;
  52873. }
  52874. }
  52875. if (this._pickable) {
  52876. var nbfaces = meshInd.length / 3;
  52877. for (i = 0; i < nbfaces; i++) {
  52878. this.pickedParticles.push({ idx: idx, faceId: i });
  52879. }
  52880. }
  52881. if (this._depthSort) {
  52882. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  52883. }
  52884. return this._copy;
  52885. };
  52886. // returns a shape array from positions array
  52887. SolidParticleSystem.prototype._posToShape = function (positions) {
  52888. var shape = [];
  52889. for (var i = 0; i < positions.length; i += 3) {
  52890. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  52891. }
  52892. return shape;
  52893. };
  52894. // returns a shapeUV array from a Vector4 uvs
  52895. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  52896. var shapeUV = [];
  52897. if (uvs) {
  52898. for (var i = 0; i < uvs.length; i++)
  52899. shapeUV.push(uvs[i]);
  52900. }
  52901. return shapeUV;
  52902. };
  52903. // adds a new particle object in the particles array
  52904. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  52905. if (bInfo === void 0) { bInfo = null; }
  52906. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  52907. this.particles.push(sp);
  52908. return sp;
  52909. };
  52910. /**
  52911. * Adds some particles to the SPS from the model shape. Returns the shape id.
  52912. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  52913. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  52914. * @param nb (positive integer) the number of particles to be created from this model
  52915. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  52916. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  52917. * @returns the number of shapes in the system
  52918. */
  52919. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  52920. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52921. var meshInd = mesh.getIndices();
  52922. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52923. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52924. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52925. var bbInfo;
  52926. if (this._particlesIntersect) {
  52927. bbInfo = mesh.getBoundingInfo();
  52928. }
  52929. var shape = this._posToShape(meshPos);
  52930. var shapeUV = this._uvsToShapeUV(meshUV);
  52931. var posfunc = options ? options.positionFunction : null;
  52932. var vtxfunc = options ? options.vertexFunction : null;
  52933. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  52934. // particles
  52935. var sp;
  52936. var currentCopy;
  52937. var idx = this.nbParticles;
  52938. for (var i = 0; i < nb; i++) {
  52939. var currentPos = this._positions.length;
  52940. var currentInd = this._indices.length;
  52941. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52942. if (this._updatable) {
  52943. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  52944. sp.position.copyFrom(currentCopy.position);
  52945. sp.rotation.copyFrom(currentCopy.rotation);
  52946. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  52947. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52948. }
  52949. if (currentCopy.color && sp.color) {
  52950. sp.color.copyFrom(currentCopy.color);
  52951. }
  52952. sp.scaling.copyFrom(currentCopy.scaling);
  52953. sp.uvs.copyFrom(currentCopy.uvs);
  52954. }
  52955. this._index += shape.length;
  52956. idx++;
  52957. }
  52958. this.nbParticles += nb;
  52959. this._shapeCounter++;
  52960. return this._shapeCounter - 1;
  52961. };
  52962. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52963. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52964. this._resetCopy();
  52965. if (particle._model._positionFunction) {
  52966. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52967. }
  52968. if (this._copy.rotationQuaternion) {
  52969. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52970. }
  52971. else {
  52972. this._yaw = this._copy.rotation.y;
  52973. this._pitch = this._copy.rotation.x;
  52974. this._roll = this._copy.rotation.z;
  52975. this._quaternionRotationYPR();
  52976. }
  52977. this._quaternionToRotationMatrix();
  52978. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52979. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52980. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52981. if (this._copy.translateFromPivot) {
  52982. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52983. }
  52984. else {
  52985. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52986. }
  52987. this._shape = particle._model._shape;
  52988. for (var pt = 0; pt < this._shape.length; pt++) {
  52989. this._vertex.x = this._shape[pt].x;
  52990. this._vertex.y = this._shape[pt].y;
  52991. this._vertex.z = this._shape[pt].z;
  52992. if (particle._model._vertexFunction) {
  52993. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52994. }
  52995. this._vertex.x *= this._copy.scaling.x;
  52996. this._vertex.y *= this._copy.scaling.y;
  52997. this._vertex.z *= this._copy.scaling.z;
  52998. this._vertex.x -= this._scaledPivot.x;
  52999. this._vertex.y -= this._scaledPivot.y;
  53000. this._vertex.z -= this._scaledPivot.z;
  53001. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53002. this._rotated.addInPlace(this._pivotBackTranslation);
  53003. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53004. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53005. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53006. }
  53007. particle.position.x = 0.0;
  53008. particle.position.y = 0.0;
  53009. particle.position.z = 0.0;
  53010. particle.rotation.x = 0.0;
  53011. particle.rotation.y = 0.0;
  53012. particle.rotation.z = 0.0;
  53013. particle.rotationQuaternion = null;
  53014. particle.scaling.x = 1.0;
  53015. particle.scaling.y = 1.0;
  53016. particle.scaling.z = 1.0;
  53017. particle.uvs.x = 0.0;
  53018. particle.uvs.y = 0.0;
  53019. particle.uvs.z = 1.0;
  53020. particle.uvs.w = 1.0;
  53021. particle.pivot.x = 0.0;
  53022. particle.pivot.y = 0.0;
  53023. particle.pivot.z = 0.0;
  53024. particle.translateFromPivot = false;
  53025. particle.parentId = null;
  53026. };
  53027. /**
  53028. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53029. * @returns the SPS.
  53030. */
  53031. SolidParticleSystem.prototype.rebuildMesh = function () {
  53032. for (var p = 0; p < this.particles.length; p++) {
  53033. this._rebuildParticle(this.particles[p]);
  53034. }
  53035. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53036. return this;
  53037. };
  53038. /**
  53039. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53040. * This method calls `updateParticle()` for each particle of the SPS.
  53041. * For an animated SPS, it is usually called within the render loop.
  53042. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53043. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53044. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53045. * @returns the SPS.
  53046. */
  53047. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53048. if (start === void 0) { start = 0; }
  53049. if (end === void 0) { end = this.nbParticles - 1; }
  53050. if (update === void 0) { update = true; }
  53051. if (!this._updatable) {
  53052. return this;
  53053. }
  53054. // custom beforeUpdate
  53055. this.beforeUpdateParticles(start, end, update);
  53056. this._cam_axisX.x = 1.0;
  53057. this._cam_axisX.y = 0.0;
  53058. this._cam_axisX.z = 0.0;
  53059. this._cam_axisY.x = 0.0;
  53060. this._cam_axisY.y = 1.0;
  53061. this._cam_axisY.z = 0.0;
  53062. this._cam_axisZ.x = 0.0;
  53063. this._cam_axisZ.y = 0.0;
  53064. this._cam_axisZ.z = 1.0;
  53065. // cases when the World Matrix is to be computed first
  53066. if (this.billboard || this._depthSort) {
  53067. this.mesh.computeWorldMatrix(true);
  53068. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53069. }
  53070. // if the particles will always face the camera
  53071. if (this.billboard) {
  53072. // compute the camera position and un-rotate it by the current mesh rotation
  53073. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53074. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53075. this._cam_axisZ.normalize();
  53076. // same for camera up vector extracted from the cam view matrix
  53077. var view = this._camera.getViewMatrix(true);
  53078. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53079. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53080. this._cam_axisY.normalize();
  53081. this._cam_axisX.normalize();
  53082. }
  53083. // if depthSort, compute the camera global position in the mesh local system
  53084. if (this._depthSort) {
  53085. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53086. }
  53087. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53088. var idx = 0; // current position index in the global array positions32
  53089. var index = 0; // position start index in the global array positions32 of the current particle
  53090. var colidx = 0; // current color index in the global array colors32
  53091. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53092. var uvidx = 0; // current uv index in the global array uvs32
  53093. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53094. var pt = 0; // current index in the particle model shape
  53095. if (this.mesh.isFacetDataEnabled) {
  53096. this._computeBoundingBox = true;
  53097. }
  53098. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53099. if (this._computeBoundingBox) {
  53100. if (start == 0 && end == this.nbParticles - 1) {
  53101. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53102. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53103. }
  53104. else {
  53105. if (this.mesh._boundingInfo) {
  53106. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53107. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53108. }
  53109. }
  53110. }
  53111. // particle loop
  53112. index = this.particles[start]._pos;
  53113. var vpos = (index / 3) | 0;
  53114. colorIndex = vpos * 4;
  53115. uvIndex = vpos * 2;
  53116. for (var p = start; p <= end; p++) {
  53117. this._particle = this.particles[p];
  53118. this._shape = this._particle._model._shape;
  53119. this._shapeUV = this._particle._model._shapeUV;
  53120. // call to custom user function to update the particle properties
  53121. this.updateParticle(this._particle);
  53122. // camera-particle distance for depth sorting
  53123. if (this._depthSort && this._depthSortParticles) {
  53124. var dsp = this.depthSortedParticles[p];
  53125. dsp.ind = this._particle._ind;
  53126. dsp.indicesLength = this._particle._model._indicesLength;
  53127. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53128. }
  53129. // skip the computations for inactive or already invisible particles
  53130. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53131. // increment indexes for the next particle
  53132. pt = this._shape.length;
  53133. index += pt * 3;
  53134. colorIndex += pt * 4;
  53135. uvIndex += pt * 2;
  53136. continue;
  53137. }
  53138. if (this._particle.isVisible) {
  53139. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53140. this._particleHasParent = (this._particle.parentId !== null);
  53141. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53142. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53143. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53144. // particle rotation matrix
  53145. if (this.billboard) {
  53146. this._particle.rotation.x = 0.0;
  53147. this._particle.rotation.y = 0.0;
  53148. }
  53149. if (this._computeParticleRotation || this.billboard) {
  53150. if (this._particle.rotationQuaternion) {
  53151. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53152. }
  53153. else {
  53154. this._yaw = this._particle.rotation.y;
  53155. this._pitch = this._particle.rotation.x;
  53156. this._roll = this._particle.rotation.z;
  53157. this._quaternionRotationYPR();
  53158. }
  53159. this._quaternionToRotationMatrix();
  53160. }
  53161. if (this._particleHasParent) {
  53162. this._parent = this.particles[this._particle.parentId];
  53163. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  53164. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  53165. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  53166. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53167. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53168. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53169. if (this._computeParticleRotation || this.billboard) {
  53170. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  53171. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  53172. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  53173. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  53174. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  53175. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  53176. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  53177. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  53178. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  53179. }
  53180. }
  53181. else {
  53182. this._particle._globalPosition.x = this._particle.position.x;
  53183. this._particle._globalPosition.y = this._particle.position.y;
  53184. this._particle._globalPosition.z = this._particle.position.z;
  53185. if (this._computeParticleRotation || this.billboard) {
  53186. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53187. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53188. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53189. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53190. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53191. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53192. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53193. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53194. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53195. }
  53196. }
  53197. if (this._particle.translateFromPivot) {
  53198. this._pivotBackTranslation.x = 0.0;
  53199. this._pivotBackTranslation.y = 0.0;
  53200. this._pivotBackTranslation.z = 0.0;
  53201. }
  53202. else {
  53203. this._pivotBackTranslation.x = this._scaledPivot.x;
  53204. this._pivotBackTranslation.y = this._scaledPivot.y;
  53205. this._pivotBackTranslation.z = this._scaledPivot.z;
  53206. }
  53207. // particle vertex loop
  53208. for (pt = 0; pt < this._shape.length; pt++) {
  53209. idx = index + pt * 3;
  53210. colidx = colorIndex + pt * 4;
  53211. uvidx = uvIndex + pt * 2;
  53212. this._vertex.x = this._shape[pt].x;
  53213. this._vertex.y = this._shape[pt].y;
  53214. this._vertex.z = this._shape[pt].z;
  53215. if (this._computeParticleVertex) {
  53216. this.updateParticleVertex(this._particle, this._vertex, pt);
  53217. }
  53218. // positions
  53219. this._vertex.x *= this._particle.scaling.x;
  53220. this._vertex.y *= this._particle.scaling.y;
  53221. this._vertex.z *= this._particle.scaling.z;
  53222. this._vertex.x -= this._scaledPivot.x;
  53223. this._vertex.y -= this._scaledPivot.y;
  53224. this._vertex.z -= this._scaledPivot.z;
  53225. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53226. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53227. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53228. this._rotated.x += this._pivotBackTranslation.x;
  53229. this._rotated.y += this._pivotBackTranslation.y;
  53230. this._rotated.z += this._pivotBackTranslation.z;
  53231. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53232. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  53233. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  53234. if (this._computeBoundingBox) {
  53235. if (this._positions32[idx] < this._minimum.x) {
  53236. this._minimum.x = this._positions32[idx];
  53237. }
  53238. if (this._positions32[idx] > this._maximum.x) {
  53239. this._maximum.x = this._positions32[idx];
  53240. }
  53241. if (this._positions32[idx + 1] < this._minimum.y) {
  53242. this._minimum.y = this._positions32[idx + 1];
  53243. }
  53244. if (this._positions32[idx + 1] > this._maximum.y) {
  53245. this._maximum.y = this._positions32[idx + 1];
  53246. }
  53247. if (this._positions32[idx + 2] < this._minimum.z) {
  53248. this._minimum.z = this._positions32[idx + 2];
  53249. }
  53250. if (this._positions32[idx + 2] > this._maximum.z) {
  53251. this._maximum.z = this._positions32[idx + 2];
  53252. }
  53253. }
  53254. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53255. if (!this._computeParticleVertex) {
  53256. this._normal.x = this._fixedNormal32[idx];
  53257. this._normal.y = this._fixedNormal32[idx + 1];
  53258. this._normal.z = this._fixedNormal32[idx + 2];
  53259. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53260. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53261. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53262. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53263. 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;
  53264. 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;
  53265. }
  53266. if (this._computeParticleColor && this._particle.color) {
  53267. this._colors32[colidx] = this._particle.color.r;
  53268. this._colors32[colidx + 1] = this._particle.color.g;
  53269. this._colors32[colidx + 2] = this._particle.color.b;
  53270. this._colors32[colidx + 3] = this._particle.color.a;
  53271. }
  53272. if (this._computeParticleTexture) {
  53273. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53274. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53275. }
  53276. }
  53277. }
  53278. else {
  53279. this._particle._stillInvisible = true; // mark the particle as invisible
  53280. for (pt = 0; pt < this._shape.length; pt++) {
  53281. idx = index + pt * 3;
  53282. colidx = colorIndex + pt * 4;
  53283. uvidx = uvIndex + pt * 2;
  53284. this._positions32[idx] = 0.0;
  53285. this._positions32[idx + 1] = 0.0;
  53286. this._positions32[idx + 2] = 0.0;
  53287. this._normals32[idx] = 0.0;
  53288. this._normals32[idx + 1] = 0.0;
  53289. this._normals32[idx + 2] = 0.0;
  53290. if (this._computeParticleColor && this._particle.color) {
  53291. this._colors32[colidx] = this._particle.color.r;
  53292. this._colors32[colidx + 1] = this._particle.color.g;
  53293. this._colors32[colidx + 2] = this._particle.color.b;
  53294. this._colors32[colidx + 3] = this._particle.color.a;
  53295. }
  53296. if (this._computeParticleTexture) {
  53297. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53298. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53299. }
  53300. }
  53301. }
  53302. // if the particle intersections must be computed : update the bbInfo
  53303. if (this._particlesIntersect) {
  53304. var bInfo = this._particle._boundingInfo;
  53305. var bBox = bInfo.boundingBox;
  53306. var bSphere = bInfo.boundingSphere;
  53307. if (!this._bSphereOnly) {
  53308. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53309. for (var b = 0; b < bBox.vectors.length; b++) {
  53310. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53311. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53312. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53313. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53314. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53315. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53316. 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;
  53317. 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;
  53318. 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;
  53319. }
  53320. bBox._update(this.mesh._worldMatrix);
  53321. }
  53322. // place and scale the particle bouding sphere in the SPS local system, then update it
  53323. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  53324. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  53325. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  53326. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  53327. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  53328. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  53329. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  53330. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  53331. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  53332. 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));
  53333. bSphere._update(this.mesh._worldMatrix);
  53334. }
  53335. // increment indexes for the next particle
  53336. index = idx + 3;
  53337. colorIndex = colidx + 4;
  53338. uvIndex = uvidx + 2;
  53339. }
  53340. // if the VBO must be updated
  53341. if (update) {
  53342. if (this._computeParticleColor) {
  53343. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53344. }
  53345. if (this._computeParticleTexture) {
  53346. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53347. }
  53348. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53349. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53350. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53351. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53352. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53353. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  53354. for (var i = 0; i < this._normals32.length; i++) {
  53355. this._fixedNormal32[i] = this._normals32[i];
  53356. }
  53357. }
  53358. if (!this.mesh.areNormalsFrozen) {
  53359. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53360. }
  53361. }
  53362. if (this._depthSort && this._depthSortParticles) {
  53363. this.depthSortedParticles.sort(this._depthSortFunction);
  53364. var dspl = this.depthSortedParticles.length;
  53365. var sorted = 0;
  53366. var lind = 0;
  53367. var sind = 0;
  53368. var sid = 0;
  53369. for (sorted = 0; sorted < dspl; sorted++) {
  53370. lind = this.depthSortedParticles[sorted].indicesLength;
  53371. sind = this.depthSortedParticles[sorted].ind;
  53372. for (var i = 0; i < lind; i++) {
  53373. this._indices32[sid] = this._indices[sind + i];
  53374. sid++;
  53375. }
  53376. }
  53377. this.mesh.updateIndices(this._indices32);
  53378. }
  53379. }
  53380. if (this._computeBoundingBox) {
  53381. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53382. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53383. }
  53384. this.afterUpdateParticles(start, end, update);
  53385. return this;
  53386. };
  53387. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53388. this._halfroll = this._roll * 0.5;
  53389. this._halfpitch = this._pitch * 0.5;
  53390. this._halfyaw = this._yaw * 0.5;
  53391. this._sinRoll = Math.sin(this._halfroll);
  53392. this._cosRoll = Math.cos(this._halfroll);
  53393. this._sinPitch = Math.sin(this._halfpitch);
  53394. this._cosPitch = Math.cos(this._halfpitch);
  53395. this._sinYaw = Math.sin(this._halfyaw);
  53396. this._cosYaw = Math.cos(this._halfyaw);
  53397. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  53398. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  53399. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  53400. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  53401. };
  53402. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  53403. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  53404. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  53405. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  53406. this._rotMatrix.m[3] = 0;
  53407. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  53408. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  53409. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  53410. this._rotMatrix.m[7] = 0;
  53411. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  53412. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  53413. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  53414. this._rotMatrix.m[11] = 0;
  53415. this._rotMatrix.m[12] = 0;
  53416. this._rotMatrix.m[13] = 0;
  53417. this._rotMatrix.m[14] = 0;
  53418. this._rotMatrix.m[15] = 1.0;
  53419. };
  53420. /**
  53421. * Disposes the SPS.
  53422. */
  53423. SolidParticleSystem.prototype.dispose = function () {
  53424. this.mesh.dispose();
  53425. this.vars = null;
  53426. // drop references to internal big arrays for the GC
  53427. this._positions = null;
  53428. this._indices = null;
  53429. this._normals = null;
  53430. this._uvs = null;
  53431. this._colors = null;
  53432. this._indices32 = null;
  53433. this._positions32 = null;
  53434. this._normals32 = null;
  53435. this._fixedNormal32 = null;
  53436. this._uvs32 = null;
  53437. this._colors32 = null;
  53438. this.pickedParticles = null;
  53439. };
  53440. /**
  53441. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53442. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53443. * @returns the SPS.
  53444. */
  53445. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53446. if (!this._isVisibilityBoxLocked) {
  53447. this.mesh.refreshBoundingInfo();
  53448. }
  53449. return this;
  53450. };
  53451. /**
  53452. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53453. * @param size the size (float) of the visibility box
  53454. * note : this doesn't lock the SPS mesh bounding box.
  53455. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53456. */
  53457. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53458. var vis = size / 2;
  53459. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53460. };
  53461. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53462. /**
  53463. * Gets whether the SPS as always visible or not
  53464. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53465. */
  53466. get: function () {
  53467. return this._alwaysVisible;
  53468. },
  53469. /**
  53470. * Sets the SPS as always visible or not
  53471. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53472. */
  53473. set: function (val) {
  53474. this._alwaysVisible = val;
  53475. this.mesh.alwaysSelectAsActiveMesh = val;
  53476. },
  53477. enumerable: true,
  53478. configurable: true
  53479. });
  53480. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  53481. /**
  53482. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53483. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53484. */
  53485. get: function () {
  53486. return this._isVisibilityBoxLocked;
  53487. },
  53488. /**
  53489. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53490. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53491. */
  53492. set: function (val) {
  53493. this._isVisibilityBoxLocked = val;
  53494. var boundingInfo = this.mesh.getBoundingInfo();
  53495. boundingInfo.isLocked = val;
  53496. },
  53497. enumerable: true,
  53498. configurable: true
  53499. });
  53500. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53501. /**
  53502. * Gets if `setParticles()` computes the particle rotations or not.
  53503. * Default value : true. The SPS is faster when it's set to false.
  53504. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53505. */
  53506. get: function () {
  53507. return this._computeParticleRotation;
  53508. },
  53509. /**
  53510. * Tells to `setParticles()` to compute the particle rotations or not.
  53511. * Default value : true. The SPS is faster when it's set to false.
  53512. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53513. */
  53514. set: function (val) {
  53515. this._computeParticleRotation = val;
  53516. },
  53517. enumerable: true,
  53518. configurable: true
  53519. });
  53520. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53521. /**
  53522. * Gets if `setParticles()` computes the particle colors or not.
  53523. * Default value : true. The SPS is faster when it's set to false.
  53524. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53525. */
  53526. get: function () {
  53527. return this._computeParticleColor;
  53528. },
  53529. /**
  53530. * Tells to `setParticles()` to compute the particle colors or not.
  53531. * Default value : true. The SPS is faster when it's set to false.
  53532. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53533. */
  53534. set: function (val) {
  53535. this._computeParticleColor = val;
  53536. },
  53537. enumerable: true,
  53538. configurable: true
  53539. });
  53540. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53541. /**
  53542. * Gets if `setParticles()` computes the particle textures or not.
  53543. * Default value : true. The SPS is faster when it's set to false.
  53544. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53545. */
  53546. get: function () {
  53547. return this._computeParticleTexture;
  53548. },
  53549. set: function (val) {
  53550. this._computeParticleTexture = val;
  53551. },
  53552. enumerable: true,
  53553. configurable: true
  53554. });
  53555. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53556. /**
  53557. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  53558. * Default value : false. The SPS is faster when it's set to false.
  53559. * Note : the particle custom vertex positions aren't stored values.
  53560. */
  53561. get: function () {
  53562. return this._computeParticleVertex;
  53563. },
  53564. /**
  53565. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53566. * Default value : false. The SPS is faster when it's set to false.
  53567. * Note : the particle custom vertex positions aren't stored values.
  53568. */
  53569. set: function (val) {
  53570. this._computeParticleVertex = val;
  53571. },
  53572. enumerable: true,
  53573. configurable: true
  53574. });
  53575. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53576. /**
  53577. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  53578. */
  53579. get: function () {
  53580. return this._computeBoundingBox;
  53581. },
  53582. /**
  53583. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53584. */
  53585. set: function (val) {
  53586. this._computeBoundingBox = val;
  53587. },
  53588. enumerable: true,
  53589. configurable: true
  53590. });
  53591. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  53592. /**
  53593. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  53594. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53595. * Default : `true`
  53596. */
  53597. get: function () {
  53598. return this._depthSortParticles;
  53599. },
  53600. /**
  53601. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  53602. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53603. * Default : `true`
  53604. */
  53605. set: function (val) {
  53606. this._depthSortParticles = val;
  53607. },
  53608. enumerable: true,
  53609. configurable: true
  53610. });
  53611. // =======================================================================
  53612. // Particle behavior logic
  53613. // these following methods may be overwritten by the user to fit his needs
  53614. /**
  53615. * This function does nothing. It may be overwritten to set all the particle first values.
  53616. * The SPS doesn't call this function, you may have to call it by your own.
  53617. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53618. */
  53619. SolidParticleSystem.prototype.initParticles = function () {
  53620. };
  53621. /**
  53622. * This function does nothing. It may be overwritten to recycle a particle.
  53623. * The SPS doesn't call this function, you may have to call it by your own.
  53624. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53625. * @param particle The particle to recycle
  53626. * @returns the recycled particle
  53627. */
  53628. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53629. return particle;
  53630. };
  53631. /**
  53632. * Updates a particle : this function should be overwritten by the user.
  53633. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53634. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53635. * @example : just set a particle position or velocity and recycle conditions
  53636. * @param particle The particle to update
  53637. * @returns the updated particle
  53638. */
  53639. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53640. return particle;
  53641. };
  53642. /**
  53643. * Updates a vertex of a particle : it can be overwritten by the user.
  53644. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53645. * @param particle the current particle
  53646. * @param vertex the current index of the current particle
  53647. * @param pt the index of the current vertex in the particle shape
  53648. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53649. * @example : just set a vertex particle position
  53650. * @returns the updated vertex
  53651. */
  53652. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53653. return vertex;
  53654. };
  53655. /**
  53656. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  53657. * This does nothing and may be overwritten by the user.
  53658. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53659. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53660. * @param update the boolean update value actually passed to setParticles()
  53661. */
  53662. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  53663. };
  53664. /**
  53665. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  53666. * This will be passed three parameters.
  53667. * This does nothing and may be overwritten by the user.
  53668. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53669. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53670. * @param update the boolean update value actually passed to setParticles()
  53671. */
  53672. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  53673. };
  53674. return SolidParticleSystem;
  53675. }());
  53676. BABYLON.SolidParticleSystem = SolidParticleSystem;
  53677. })(BABYLON || (BABYLON = {}));
  53678. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  53679. var BABYLON;
  53680. (function (BABYLON) {
  53681. var ShaderMaterial = /** @class */ (function (_super) {
  53682. __extends(ShaderMaterial, _super);
  53683. function ShaderMaterial(name, scene, shaderPath, options) {
  53684. var _this = _super.call(this, name, scene) || this;
  53685. _this._textures = {};
  53686. _this._textureArrays = {};
  53687. _this._floats = {};
  53688. _this._ints = {};
  53689. _this._floatsArrays = {};
  53690. _this._colors3 = {};
  53691. _this._colors3Arrays = {};
  53692. _this._colors4 = {};
  53693. _this._vectors2 = {};
  53694. _this._vectors3 = {};
  53695. _this._vectors4 = {};
  53696. _this._matrices = {};
  53697. _this._matrices3x3 = {};
  53698. _this._matrices2x2 = {};
  53699. _this._vectors2Arrays = {};
  53700. _this._vectors3Arrays = {};
  53701. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  53702. _this._shaderPath = shaderPath;
  53703. options.needAlphaBlending = options.needAlphaBlending || false;
  53704. options.needAlphaTesting = options.needAlphaTesting || false;
  53705. options.attributes = options.attributes || ["position", "normal", "uv"];
  53706. options.uniforms = options.uniforms || ["worldViewProjection"];
  53707. options.uniformBuffers = options.uniformBuffers || [];
  53708. options.samplers = options.samplers || [];
  53709. options.defines = options.defines || [];
  53710. _this._options = options;
  53711. return _this;
  53712. }
  53713. ShaderMaterial.prototype.getClassName = function () {
  53714. return "ShaderMaterial";
  53715. };
  53716. ShaderMaterial.prototype.needAlphaBlending = function () {
  53717. return this._options.needAlphaBlending;
  53718. };
  53719. ShaderMaterial.prototype.needAlphaTesting = function () {
  53720. return this._options.needAlphaTesting;
  53721. };
  53722. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  53723. if (this._options.uniforms.indexOf(uniformName) === -1) {
  53724. this._options.uniforms.push(uniformName);
  53725. }
  53726. };
  53727. ShaderMaterial.prototype.setTexture = function (name, texture) {
  53728. if (this._options.samplers.indexOf(name) === -1) {
  53729. this._options.samplers.push(name);
  53730. }
  53731. this._textures[name] = texture;
  53732. return this;
  53733. };
  53734. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  53735. if (this._options.samplers.indexOf(name) === -1) {
  53736. this._options.samplers.push(name);
  53737. }
  53738. this._checkUniform(name);
  53739. this._textureArrays[name] = textures;
  53740. return this;
  53741. };
  53742. ShaderMaterial.prototype.setFloat = function (name, value) {
  53743. this._checkUniform(name);
  53744. this._floats[name] = value;
  53745. return this;
  53746. };
  53747. ShaderMaterial.prototype.setInt = function (name, value) {
  53748. this._checkUniform(name);
  53749. this._ints[name] = value;
  53750. return this;
  53751. };
  53752. ShaderMaterial.prototype.setFloats = function (name, value) {
  53753. this._checkUniform(name);
  53754. this._floatsArrays[name] = value;
  53755. return this;
  53756. };
  53757. ShaderMaterial.prototype.setColor3 = function (name, value) {
  53758. this._checkUniform(name);
  53759. this._colors3[name] = value;
  53760. return this;
  53761. };
  53762. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  53763. this._checkUniform(name);
  53764. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  53765. color.toArray(arr, arr.length);
  53766. return arr;
  53767. }, []);
  53768. return this;
  53769. };
  53770. ShaderMaterial.prototype.setColor4 = function (name, value) {
  53771. this._checkUniform(name);
  53772. this._colors4[name] = value;
  53773. return this;
  53774. };
  53775. ShaderMaterial.prototype.setVector2 = function (name, value) {
  53776. this._checkUniform(name);
  53777. this._vectors2[name] = value;
  53778. return this;
  53779. };
  53780. ShaderMaterial.prototype.setVector3 = function (name, value) {
  53781. this._checkUniform(name);
  53782. this._vectors3[name] = value;
  53783. return this;
  53784. };
  53785. ShaderMaterial.prototype.setVector4 = function (name, value) {
  53786. this._checkUniform(name);
  53787. this._vectors4[name] = value;
  53788. return this;
  53789. };
  53790. ShaderMaterial.prototype.setMatrix = function (name, value) {
  53791. this._checkUniform(name);
  53792. this._matrices[name] = value;
  53793. return this;
  53794. };
  53795. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  53796. this._checkUniform(name);
  53797. this._matrices3x3[name] = value;
  53798. return this;
  53799. };
  53800. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  53801. this._checkUniform(name);
  53802. this._matrices2x2[name] = value;
  53803. return this;
  53804. };
  53805. ShaderMaterial.prototype.setArray2 = function (name, value) {
  53806. this._checkUniform(name);
  53807. this._vectors2Arrays[name] = value;
  53808. return this;
  53809. };
  53810. ShaderMaterial.prototype.setArray3 = function (name, value) {
  53811. this._checkUniform(name);
  53812. this._vectors3Arrays[name] = value;
  53813. return this;
  53814. };
  53815. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53816. if (!mesh) {
  53817. return true;
  53818. }
  53819. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  53820. return false;
  53821. }
  53822. return false;
  53823. };
  53824. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  53825. var scene = this.getScene();
  53826. var engine = scene.getEngine();
  53827. if (!this.checkReadyOnEveryCall) {
  53828. if (this._renderId === scene.getRenderId()) {
  53829. if (this._checkCache(scene, mesh, useInstances)) {
  53830. return true;
  53831. }
  53832. }
  53833. }
  53834. // Instances
  53835. var defines = [];
  53836. var attribs = [];
  53837. var fallbacks = new BABYLON.EffectFallbacks();
  53838. if (useInstances) {
  53839. defines.push("#define INSTANCES");
  53840. }
  53841. for (var index = 0; index < this._options.defines.length; index++) {
  53842. defines.push(this._options.defines[index]);
  53843. }
  53844. for (var index = 0; index < this._options.attributes.length; index++) {
  53845. attribs.push(this._options.attributes[index]);
  53846. }
  53847. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53848. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53849. defines.push("#define VERTEXCOLOR");
  53850. }
  53851. // Bones
  53852. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  53853. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53854. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53855. if (mesh.numBoneInfluencers > 4) {
  53856. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53857. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53858. }
  53859. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53860. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53861. fallbacks.addCPUSkinningFallback(0, mesh);
  53862. if (this._options.uniforms.indexOf("mBones") === -1) {
  53863. this._options.uniforms.push("mBones");
  53864. }
  53865. }
  53866. else {
  53867. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53868. }
  53869. // Textures
  53870. for (var name in this._textures) {
  53871. if (!this._textures[name].isReady()) {
  53872. return false;
  53873. }
  53874. }
  53875. // Alpha test
  53876. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  53877. defines.push("#define ALPHATEST");
  53878. }
  53879. var previousEffect = this._effect;
  53880. var join = defines.join("\n");
  53881. this._effect = engine.createEffect(this._shaderPath, {
  53882. attributes: attribs,
  53883. uniformsNames: this._options.uniforms,
  53884. uniformBuffersNames: this._options.uniformBuffers,
  53885. samplers: this._options.samplers,
  53886. defines: join,
  53887. fallbacks: fallbacks,
  53888. onCompiled: this.onCompiled,
  53889. onError: this.onError
  53890. }, engine);
  53891. if (!this._effect.isReady()) {
  53892. return false;
  53893. }
  53894. if (previousEffect !== this._effect) {
  53895. scene.resetCachedMaterial();
  53896. }
  53897. this._renderId = scene.getRenderId();
  53898. return true;
  53899. };
  53900. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53901. var scene = this.getScene();
  53902. if (!this._effect) {
  53903. return;
  53904. }
  53905. if (this._options.uniforms.indexOf("world") !== -1) {
  53906. this._effect.setMatrix("world", world);
  53907. }
  53908. if (this._options.uniforms.indexOf("worldView") !== -1) {
  53909. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  53910. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  53911. }
  53912. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  53913. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  53914. }
  53915. };
  53916. ShaderMaterial.prototype.bind = function (world, mesh) {
  53917. // Std values
  53918. this.bindOnlyWorldMatrix(world);
  53919. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  53920. if (this._options.uniforms.indexOf("view") !== -1) {
  53921. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  53922. }
  53923. if (this._options.uniforms.indexOf("projection") !== -1) {
  53924. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  53925. }
  53926. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  53927. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  53928. }
  53929. // Bones
  53930. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53931. var name;
  53932. // Texture
  53933. for (name in this._textures) {
  53934. this._effect.setTexture(name, this._textures[name]);
  53935. }
  53936. // Texture arrays
  53937. for (name in this._textureArrays) {
  53938. this._effect.setTextureArray(name, this._textureArrays[name]);
  53939. }
  53940. // Int
  53941. for (name in this._ints) {
  53942. this._effect.setInt(name, this._ints[name]);
  53943. }
  53944. // Float
  53945. for (name in this._floats) {
  53946. this._effect.setFloat(name, this._floats[name]);
  53947. }
  53948. // Floats
  53949. for (name in this._floatsArrays) {
  53950. this._effect.setArray(name, this._floatsArrays[name]);
  53951. }
  53952. // Color3
  53953. for (name in this._colors3) {
  53954. this._effect.setColor3(name, this._colors3[name]);
  53955. }
  53956. for (name in this._colors3Arrays) {
  53957. this._effect.setArray3(name, this._colors3Arrays[name]);
  53958. }
  53959. // Color4
  53960. for (name in this._colors4) {
  53961. var color = this._colors4[name];
  53962. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  53963. }
  53964. // Vector2
  53965. for (name in this._vectors2) {
  53966. this._effect.setVector2(name, this._vectors2[name]);
  53967. }
  53968. // Vector3
  53969. for (name in this._vectors3) {
  53970. this._effect.setVector3(name, this._vectors3[name]);
  53971. }
  53972. // Vector4
  53973. for (name in this._vectors4) {
  53974. this._effect.setVector4(name, this._vectors4[name]);
  53975. }
  53976. // Matrix
  53977. for (name in this._matrices) {
  53978. this._effect.setMatrix(name, this._matrices[name]);
  53979. }
  53980. // Matrix 3x3
  53981. for (name in this._matrices3x3) {
  53982. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  53983. }
  53984. // Matrix 2x2
  53985. for (name in this._matrices2x2) {
  53986. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  53987. }
  53988. // Vector2Array
  53989. for (name in this._vectors2Arrays) {
  53990. this._effect.setArray2(name, this._vectors2Arrays[name]);
  53991. }
  53992. // Vector3Array
  53993. for (name in this._vectors3Arrays) {
  53994. this._effect.setArray3(name, this._vectors3Arrays[name]);
  53995. }
  53996. }
  53997. this._afterBind(mesh);
  53998. };
  53999. ShaderMaterial.prototype.getActiveTextures = function () {
  54000. var activeTextures = _super.prototype.getActiveTextures.call(this);
  54001. for (var name in this._textures) {
  54002. activeTextures.push(this._textures[name]);
  54003. }
  54004. for (var name in this._textureArrays) {
  54005. var array = this._textureArrays[name];
  54006. for (var index = 0; index < array.length; index++) {
  54007. activeTextures.push(array[index]);
  54008. }
  54009. }
  54010. return activeTextures;
  54011. };
  54012. ShaderMaterial.prototype.hasTexture = function (texture) {
  54013. if (_super.prototype.hasTexture.call(this, texture)) {
  54014. return true;
  54015. }
  54016. for (var name in this._textures) {
  54017. if (this._textures[name] === texture) {
  54018. return true;
  54019. }
  54020. }
  54021. for (var name in this._textureArrays) {
  54022. var array = this._textureArrays[name];
  54023. for (var index = 0; index < array.length; index++) {
  54024. if (array[index] === texture) {
  54025. return true;
  54026. }
  54027. }
  54028. }
  54029. return false;
  54030. };
  54031. ShaderMaterial.prototype.clone = function (name) {
  54032. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  54033. return newShaderMaterial;
  54034. };
  54035. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54036. if (forceDisposeTextures) {
  54037. var name;
  54038. for (name in this._textures) {
  54039. this._textures[name].dispose();
  54040. }
  54041. for (name in this._textureArrays) {
  54042. var array = this._textureArrays[name];
  54043. for (var index = 0; index < array.length; index++) {
  54044. array[index].dispose();
  54045. }
  54046. }
  54047. }
  54048. this._textures = {};
  54049. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54050. };
  54051. ShaderMaterial.prototype.serialize = function () {
  54052. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54053. serializationObject.customType = "BABYLON.ShaderMaterial";
  54054. serializationObject.options = this._options;
  54055. serializationObject.shaderPath = this._shaderPath;
  54056. var name;
  54057. // Texture
  54058. serializationObject.textures = {};
  54059. for (name in this._textures) {
  54060. serializationObject.textures[name] = this._textures[name].serialize();
  54061. }
  54062. // Texture arrays
  54063. serializationObject.textureArrays = {};
  54064. for (name in this._textureArrays) {
  54065. serializationObject.textureArrays[name] = [];
  54066. var array = this._textureArrays[name];
  54067. for (var index = 0; index < array.length; index++) {
  54068. serializationObject.textureArrays[name].push(array[index].serialize());
  54069. }
  54070. }
  54071. // Float
  54072. serializationObject.floats = {};
  54073. for (name in this._floats) {
  54074. serializationObject.floats[name] = this._floats[name];
  54075. }
  54076. // Float s
  54077. serializationObject.FloatArrays = {};
  54078. for (name in this._floatsArrays) {
  54079. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54080. }
  54081. // Color3
  54082. serializationObject.colors3 = {};
  54083. for (name in this._colors3) {
  54084. serializationObject.colors3[name] = this._colors3[name].asArray();
  54085. }
  54086. // Color3 array
  54087. serializationObject.colors3Arrays = {};
  54088. for (name in this._colors3Arrays) {
  54089. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54090. }
  54091. // Color4
  54092. serializationObject.colors4 = {};
  54093. for (name in this._colors4) {
  54094. serializationObject.colors4[name] = this._colors4[name].asArray();
  54095. }
  54096. // Vector2
  54097. serializationObject.vectors2 = {};
  54098. for (name in this._vectors2) {
  54099. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54100. }
  54101. // Vector3
  54102. serializationObject.vectors3 = {};
  54103. for (name in this._vectors3) {
  54104. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54105. }
  54106. // Vector4
  54107. serializationObject.vectors4 = {};
  54108. for (name in this._vectors4) {
  54109. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54110. }
  54111. // Matrix
  54112. serializationObject.matrices = {};
  54113. for (name in this._matrices) {
  54114. serializationObject.matrices[name] = this._matrices[name].asArray();
  54115. }
  54116. // Matrix 3x3
  54117. serializationObject.matrices3x3 = {};
  54118. for (name in this._matrices3x3) {
  54119. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54120. }
  54121. // Matrix 2x2
  54122. serializationObject.matrices2x2 = {};
  54123. for (name in this._matrices2x2) {
  54124. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54125. }
  54126. // Vector2Array
  54127. serializationObject.vectors2Arrays = {};
  54128. for (name in this._vectors2Arrays) {
  54129. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54130. }
  54131. // Vector3Array
  54132. serializationObject.vectors3Arrays = {};
  54133. for (name in this._vectors3Arrays) {
  54134. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54135. }
  54136. return serializationObject;
  54137. };
  54138. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54139. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54140. var name;
  54141. // Texture
  54142. for (name in source.textures) {
  54143. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54144. }
  54145. // Texture arrays
  54146. for (name in source.textureArrays) {
  54147. var array = source.textureArrays[name];
  54148. var textureArray = new Array();
  54149. for (var index = 0; index < array.length; index++) {
  54150. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54151. }
  54152. material.setTextureArray(name, textureArray);
  54153. }
  54154. // Float
  54155. for (name in source.floats) {
  54156. material.setFloat(name, source.floats[name]);
  54157. }
  54158. // Float s
  54159. for (name in source.floatsArrays) {
  54160. material.setFloats(name, source.floatsArrays[name]);
  54161. }
  54162. // Color3
  54163. for (name in source.colors3) {
  54164. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54165. }
  54166. // Color3 arrays
  54167. for (name in source.colors3Arrays) {
  54168. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54169. if (i % 3 === 0) {
  54170. arr.push([num]);
  54171. }
  54172. else {
  54173. arr[arr.length - 1].push(num);
  54174. }
  54175. return arr;
  54176. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54177. material.setColor3Array(name, colors);
  54178. }
  54179. // Color4
  54180. for (name in source.colors4) {
  54181. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54182. }
  54183. // Vector2
  54184. for (name in source.vectors2) {
  54185. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54186. }
  54187. // Vector3
  54188. for (name in source.vectors3) {
  54189. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54190. }
  54191. // Vector4
  54192. for (name in source.vectors4) {
  54193. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54194. }
  54195. // Matrix
  54196. for (name in source.matrices) {
  54197. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54198. }
  54199. // Matrix 3x3
  54200. for (name in source.matrices3x3) {
  54201. material.setMatrix3x3(name, source.matrices3x3[name]);
  54202. }
  54203. // Matrix 2x2
  54204. for (name in source.matrices2x2) {
  54205. material.setMatrix2x2(name, source.matrices2x2[name]);
  54206. }
  54207. // Vector2Array
  54208. for (name in source.vectors2Arrays) {
  54209. material.setArray2(name, source.vectors2Arrays[name]);
  54210. }
  54211. // Vector3Array
  54212. for (name in source.vectors3Arrays) {
  54213. material.setArray3(name, source.vectors3Arrays[name]);
  54214. }
  54215. return material;
  54216. };
  54217. return ShaderMaterial;
  54218. }(BABYLON.Material));
  54219. BABYLON.ShaderMaterial = ShaderMaterial;
  54220. })(BABYLON || (BABYLON = {}));
  54221. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54222. var BABYLON;
  54223. (function (BABYLON) {
  54224. var GroundMesh = /** @class */ (function (_super) {
  54225. __extends(GroundMesh, _super);
  54226. function GroundMesh(name, scene) {
  54227. var _this = _super.call(this, name, scene) || this;
  54228. _this.generateOctree = false;
  54229. return _this;
  54230. }
  54231. GroundMesh.prototype.getClassName = function () {
  54232. return "GroundMesh";
  54233. };
  54234. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54235. get: function () {
  54236. return Math.min(this._subdivisionsX, this._subdivisionsY);
  54237. },
  54238. enumerable: true,
  54239. configurable: true
  54240. });
  54241. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  54242. get: function () {
  54243. return this._subdivisionsX;
  54244. },
  54245. enumerable: true,
  54246. configurable: true
  54247. });
  54248. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54249. get: function () {
  54250. return this._subdivisionsY;
  54251. },
  54252. enumerable: true,
  54253. configurable: true
  54254. });
  54255. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54256. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54257. this._subdivisionsX = chunksCount;
  54258. this._subdivisionsY = chunksCount;
  54259. this.subdivide(chunksCount);
  54260. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54261. };
  54262. /**
  54263. * Returns a height (y) value in the Worl system :
  54264. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54265. * Returns the ground y position if (x, z) are outside the ground surface.
  54266. */
  54267. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54268. var world = this.getWorldMatrix();
  54269. var invMat = BABYLON.Tmp.Matrix[5];
  54270. world.invertToRef(invMat);
  54271. var tmpVect = BABYLON.Tmp.Vector3[8];
  54272. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54273. x = tmpVect.x;
  54274. z = tmpVect.z;
  54275. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54276. return this.position.y;
  54277. }
  54278. if (!this._heightQuads || this._heightQuads.length == 0) {
  54279. this._initHeightQuads();
  54280. this._computeHeightQuads();
  54281. }
  54282. var facet = this._getFacetAt(x, z);
  54283. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54284. // return y in the World system
  54285. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54286. return tmpVect.y;
  54287. };
  54288. /**
  54289. * Returns a normalized vector (Vector3) orthogonal to the ground
  54290. * at the ground coordinates (x, z) expressed in the World system.
  54291. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54292. */
  54293. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54294. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54295. this.getNormalAtCoordinatesToRef(x, z, normal);
  54296. return normal;
  54297. };
  54298. /**
  54299. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54300. * at the ground coordinates (x, z) expressed in the World system.
  54301. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54302. * Returns the GroundMesh.
  54303. */
  54304. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54305. var world = this.getWorldMatrix();
  54306. var tmpMat = BABYLON.Tmp.Matrix[5];
  54307. world.invertToRef(tmpMat);
  54308. var tmpVect = BABYLON.Tmp.Vector3[8];
  54309. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54310. x = tmpVect.x;
  54311. z = tmpVect.z;
  54312. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54313. return this;
  54314. }
  54315. if (!this._heightQuads || this._heightQuads.length == 0) {
  54316. this._initHeightQuads();
  54317. this._computeHeightQuads();
  54318. }
  54319. var facet = this._getFacetAt(x, z);
  54320. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  54321. return this;
  54322. };
  54323. /**
  54324. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  54325. * if the ground has been updated.
  54326. * This can be used in the render loop.
  54327. * Returns the GroundMesh.
  54328. */
  54329. GroundMesh.prototype.updateCoordinateHeights = function () {
  54330. if (!this._heightQuads || this._heightQuads.length == 0) {
  54331. this._initHeightQuads();
  54332. }
  54333. this._computeHeightQuads();
  54334. return this;
  54335. };
  54336. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  54337. GroundMesh.prototype._getFacetAt = function (x, z) {
  54338. // retrieve col and row from x, z coordinates in the ground local system
  54339. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  54340. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  54341. var quad = this._heightQuads[row * this._subdivisionsX + col];
  54342. var facet;
  54343. if (z < quad.slope.x * x + quad.slope.y) {
  54344. facet = quad.facet1;
  54345. }
  54346. else {
  54347. facet = quad.facet2;
  54348. }
  54349. return facet;
  54350. };
  54351. // Creates and populates the heightMap array with "facet" elements :
  54352. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  54353. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54354. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54355. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54356. // Returns the GroundMesh.
  54357. GroundMesh.prototype._initHeightQuads = function () {
  54358. var subdivisionsX = this._subdivisionsX;
  54359. var subdivisionsY = this._subdivisionsY;
  54360. this._heightQuads = new Array();
  54361. for (var row = 0; row < subdivisionsY; row++) {
  54362. for (var col = 0; col < subdivisionsX; col++) {
  54363. 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) };
  54364. this._heightQuads[row * subdivisionsX + col] = quad;
  54365. }
  54366. }
  54367. return this;
  54368. };
  54369. // Compute each quad element values and update the the heightMap array :
  54370. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54371. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54372. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54373. // Returns the GroundMesh.
  54374. GroundMesh.prototype._computeHeightQuads = function () {
  54375. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54376. if (!positions) {
  54377. return this;
  54378. }
  54379. var v1 = BABYLON.Tmp.Vector3[3];
  54380. var v2 = BABYLON.Tmp.Vector3[2];
  54381. var v3 = BABYLON.Tmp.Vector3[1];
  54382. var v4 = BABYLON.Tmp.Vector3[0];
  54383. var v1v2 = BABYLON.Tmp.Vector3[4];
  54384. var v1v3 = BABYLON.Tmp.Vector3[5];
  54385. var v1v4 = BABYLON.Tmp.Vector3[6];
  54386. var norm1 = BABYLON.Tmp.Vector3[7];
  54387. var norm2 = BABYLON.Tmp.Vector3[8];
  54388. var i = 0;
  54389. var j = 0;
  54390. var k = 0;
  54391. var cd = 0; // 2D slope coefficient : z = cd * x + h
  54392. var h = 0;
  54393. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  54394. var d2 = 0;
  54395. var subdivisionsX = this._subdivisionsX;
  54396. var subdivisionsY = this._subdivisionsY;
  54397. for (var row = 0; row < subdivisionsY; row++) {
  54398. for (var col = 0; col < subdivisionsX; col++) {
  54399. i = col * 3;
  54400. j = row * (subdivisionsX + 1) * 3;
  54401. k = (row + 1) * (subdivisionsX + 1) * 3;
  54402. v1.x = positions[j + i];
  54403. v1.y = positions[j + i + 1];
  54404. v1.z = positions[j + i + 2];
  54405. v2.x = positions[j + i + 3];
  54406. v2.y = positions[j + i + 4];
  54407. v2.z = positions[j + i + 5];
  54408. v3.x = positions[k + i];
  54409. v3.y = positions[k + i + 1];
  54410. v3.z = positions[k + i + 2];
  54411. v4.x = positions[k + i + 3];
  54412. v4.y = positions[k + i + 4];
  54413. v4.z = positions[k + i + 5];
  54414. // 2D slope V1V4
  54415. cd = (v4.z - v1.z) / (v4.x - v1.x);
  54416. h = v1.z - cd * v1.x; // v1 belongs to the slope
  54417. // facet equations :
  54418. // we compute each facet normal vector
  54419. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  54420. // we compute the value d by applying the equation to v1 which belongs to the plane
  54421. // then we store the facet equation in a Vector4
  54422. v2.subtractToRef(v1, v1v2);
  54423. v3.subtractToRef(v1, v1v3);
  54424. v4.subtractToRef(v1, v1v4);
  54425. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  54426. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  54427. norm1.normalize();
  54428. norm2.normalize();
  54429. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  54430. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  54431. var quad = this._heightQuads[row * subdivisionsX + col];
  54432. quad.slope.copyFromFloats(cd, h);
  54433. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  54434. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  54435. }
  54436. }
  54437. return this;
  54438. };
  54439. GroundMesh.prototype.serialize = function (serializationObject) {
  54440. _super.prototype.serialize.call(this, serializationObject);
  54441. serializationObject.subdivisionsX = this._subdivisionsX;
  54442. serializationObject.subdivisionsY = this._subdivisionsY;
  54443. serializationObject.minX = this._minX;
  54444. serializationObject.maxX = this._maxX;
  54445. serializationObject.minZ = this._minZ;
  54446. serializationObject.maxZ = this._maxZ;
  54447. serializationObject.width = this._width;
  54448. serializationObject.height = this._height;
  54449. };
  54450. GroundMesh.Parse = function (parsedMesh, scene) {
  54451. var result = new GroundMesh(parsedMesh.name, scene);
  54452. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  54453. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  54454. result._minX = parsedMesh.minX;
  54455. result._maxX = parsedMesh.maxX;
  54456. result._minZ = parsedMesh.minZ;
  54457. result._maxZ = parsedMesh.maxZ;
  54458. result._width = parsedMesh.width;
  54459. result._height = parsedMesh.height;
  54460. return result;
  54461. };
  54462. return GroundMesh;
  54463. }(BABYLON.Mesh));
  54464. BABYLON.GroundMesh = GroundMesh;
  54465. })(BABYLON || (BABYLON = {}));
  54466. //# sourceMappingURL=babylon.groundMesh.js.map
  54467. var BABYLON;
  54468. (function (BABYLON) {
  54469. /**
  54470. * Creates an instance based on a source mesh.
  54471. */
  54472. var InstancedMesh = /** @class */ (function (_super) {
  54473. __extends(InstancedMesh, _super);
  54474. function InstancedMesh(name, source) {
  54475. var _this = _super.call(this, name, source.getScene()) || this;
  54476. source.instances.push(_this);
  54477. _this._sourceMesh = source;
  54478. _this.position.copyFrom(source.position);
  54479. _this.rotation.copyFrom(source.rotation);
  54480. _this.scaling.copyFrom(source.scaling);
  54481. if (source.rotationQuaternion) {
  54482. _this.rotationQuaternion = source.rotationQuaternion.clone();
  54483. }
  54484. _this.infiniteDistance = source.infiniteDistance;
  54485. _this.setPivotMatrix(source.getPivotMatrix());
  54486. _this.refreshBoundingInfo();
  54487. _this._syncSubMeshes();
  54488. return _this;
  54489. }
  54490. /**
  54491. * Returns the string "InstancedMesh".
  54492. */
  54493. InstancedMesh.prototype.getClassName = function () {
  54494. return "InstancedMesh";
  54495. };
  54496. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  54497. // Methods
  54498. get: function () {
  54499. return this._sourceMesh.receiveShadows;
  54500. },
  54501. enumerable: true,
  54502. configurable: true
  54503. });
  54504. Object.defineProperty(InstancedMesh.prototype, "material", {
  54505. get: function () {
  54506. return this._sourceMesh.material;
  54507. },
  54508. enumerable: true,
  54509. configurable: true
  54510. });
  54511. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  54512. get: function () {
  54513. return this._sourceMesh.visibility;
  54514. },
  54515. enumerable: true,
  54516. configurable: true
  54517. });
  54518. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  54519. get: function () {
  54520. return this._sourceMesh.skeleton;
  54521. },
  54522. enumerable: true,
  54523. configurable: true
  54524. });
  54525. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  54526. get: function () {
  54527. return this._sourceMesh.renderingGroupId;
  54528. },
  54529. set: function (value) {
  54530. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  54531. return;
  54532. }
  54533. //no-op with warning
  54534. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  54535. },
  54536. enumerable: true,
  54537. configurable: true
  54538. });
  54539. /**
  54540. * Returns the total number of vertices (integer).
  54541. */
  54542. InstancedMesh.prototype.getTotalVertices = function () {
  54543. return this._sourceMesh.getTotalVertices();
  54544. };
  54545. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  54546. get: function () {
  54547. return this._sourceMesh;
  54548. },
  54549. enumerable: true,
  54550. configurable: true
  54551. });
  54552. /**
  54553. * Is this node ready to be used/rendered
  54554. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  54555. * @return {boolean} is it ready
  54556. */
  54557. InstancedMesh.prototype.isReady = function (completeCheck) {
  54558. if (completeCheck === void 0) { completeCheck = false; }
  54559. return this._sourceMesh.isReady(completeCheck, true);
  54560. };
  54561. /**
  54562. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  54563. */
  54564. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  54565. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  54566. };
  54567. /**
  54568. * Sets the vertex data of the mesh geometry for the requested `kind`.
  54569. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  54570. * The `data` are either a numeric array either a Float32Array.
  54571. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  54572. * 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).
  54573. * Note that a new underlying VertexBuffer object is created each call.
  54574. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  54575. *
  54576. * Possible `kind` values :
  54577. * - BABYLON.VertexBuffer.PositionKind
  54578. * - BABYLON.VertexBuffer.UVKind
  54579. * - BABYLON.VertexBuffer.UV2Kind
  54580. * - BABYLON.VertexBuffer.UV3Kind
  54581. * - BABYLON.VertexBuffer.UV4Kind
  54582. * - BABYLON.VertexBuffer.UV5Kind
  54583. * - BABYLON.VertexBuffer.UV6Kind
  54584. * - BABYLON.VertexBuffer.ColorKind
  54585. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54586. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54587. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54588. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54589. *
  54590. * Returns the Mesh.
  54591. */
  54592. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  54593. if (this.sourceMesh) {
  54594. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  54595. }
  54596. return this.sourceMesh;
  54597. };
  54598. /**
  54599. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  54600. * If the mesh has no geometry, it is simply returned as it is.
  54601. * The `data` are either a numeric array either a Float32Array.
  54602. * No new underlying VertexBuffer object is created.
  54603. * 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.
  54604. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  54605. *
  54606. * Possible `kind` values :
  54607. * - BABYLON.VertexBuffer.PositionKind
  54608. * - BABYLON.VertexBuffer.UVKind
  54609. * - BABYLON.VertexBuffer.UV2Kind
  54610. * - BABYLON.VertexBuffer.UV3Kind
  54611. * - BABYLON.VertexBuffer.UV4Kind
  54612. * - BABYLON.VertexBuffer.UV5Kind
  54613. * - BABYLON.VertexBuffer.UV6Kind
  54614. * - BABYLON.VertexBuffer.ColorKind
  54615. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54616. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54617. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54618. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54619. *
  54620. * Returns the Mesh.
  54621. */
  54622. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  54623. if (this.sourceMesh) {
  54624. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  54625. }
  54626. return this.sourceMesh;
  54627. };
  54628. /**
  54629. * Sets the mesh indices.
  54630. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  54631. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  54632. * This method creates a new index buffer each call.
  54633. * Returns the Mesh.
  54634. */
  54635. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  54636. if (totalVertices === void 0) { totalVertices = null; }
  54637. if (this.sourceMesh) {
  54638. this.sourceMesh.setIndices(indices, totalVertices);
  54639. }
  54640. return this.sourceMesh;
  54641. };
  54642. /**
  54643. * Boolean : True if the mesh owns the requested kind of data.
  54644. */
  54645. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  54646. return this._sourceMesh.isVerticesDataPresent(kind);
  54647. };
  54648. /**
  54649. * Returns an array of indices (IndicesArray).
  54650. */
  54651. InstancedMesh.prototype.getIndices = function () {
  54652. return this._sourceMesh.getIndices();
  54653. };
  54654. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  54655. get: function () {
  54656. return this._sourceMesh._positions;
  54657. },
  54658. enumerable: true,
  54659. configurable: true
  54660. });
  54661. /**
  54662. * Sets a new updated BoundingInfo to the mesh.
  54663. * Returns the mesh.
  54664. */
  54665. InstancedMesh.prototype.refreshBoundingInfo = function () {
  54666. var meshBB = this._sourceMesh.getBoundingInfo();
  54667. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  54668. this._updateBoundingInfo();
  54669. return this;
  54670. };
  54671. InstancedMesh.prototype._preActivate = function () {
  54672. if (this._currentLOD) {
  54673. this._currentLOD._preActivate();
  54674. }
  54675. return this;
  54676. };
  54677. InstancedMesh.prototype._activate = function (renderId) {
  54678. if (this._currentLOD) {
  54679. this._currentLOD._registerInstanceForRenderId(this, renderId);
  54680. }
  54681. return this;
  54682. };
  54683. /**
  54684. * Returns the current associated LOD AbstractMesh.
  54685. */
  54686. InstancedMesh.prototype.getLOD = function (camera) {
  54687. if (!camera) {
  54688. return this;
  54689. }
  54690. var boundingInfo = this.getBoundingInfo();
  54691. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  54692. if (this._currentLOD === this.sourceMesh) {
  54693. return this;
  54694. }
  54695. return this._currentLOD;
  54696. };
  54697. InstancedMesh.prototype._syncSubMeshes = function () {
  54698. this.releaseSubMeshes();
  54699. if (this._sourceMesh.subMeshes) {
  54700. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  54701. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  54702. }
  54703. }
  54704. return this;
  54705. };
  54706. InstancedMesh.prototype._generatePointsArray = function () {
  54707. return this._sourceMesh._generatePointsArray();
  54708. };
  54709. /**
  54710. * Creates a new InstancedMesh from the current mesh.
  54711. * - name (string) : the cloned mesh name
  54712. * - newParent (optional Node) : the optional Node to parent the clone to.
  54713. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  54714. *
  54715. * Returns the clone.
  54716. */
  54717. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54718. var result = this._sourceMesh.createInstance(name);
  54719. // Deep copy
  54720. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  54721. // Bounding info
  54722. this.refreshBoundingInfo();
  54723. // Parent
  54724. if (newParent) {
  54725. result.parent = newParent;
  54726. }
  54727. if (!doNotCloneChildren) {
  54728. // Children
  54729. for (var index = 0; index < this.getScene().meshes.length; index++) {
  54730. var mesh = this.getScene().meshes[index];
  54731. if (mesh.parent === this) {
  54732. mesh.clone(mesh.name, result);
  54733. }
  54734. }
  54735. }
  54736. result.computeWorldMatrix(true);
  54737. return result;
  54738. };
  54739. /**
  54740. * Disposes the InstancedMesh.
  54741. * Returns nothing.
  54742. */
  54743. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  54744. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  54745. // Remove from mesh
  54746. var index = this._sourceMesh.instances.indexOf(this);
  54747. this._sourceMesh.instances.splice(index, 1);
  54748. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  54749. };
  54750. return InstancedMesh;
  54751. }(BABYLON.AbstractMesh));
  54752. BABYLON.InstancedMesh = InstancedMesh;
  54753. })(BABYLON || (BABYLON = {}));
  54754. //# sourceMappingURL=babylon.instancedMesh.js.map
  54755. var BABYLON;
  54756. (function (BABYLON) {
  54757. var LinesMesh = /** @class */ (function (_super) {
  54758. __extends(LinesMesh, _super);
  54759. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  54760. if (scene === void 0) { scene = null; }
  54761. if (parent === void 0) { parent = null; }
  54762. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  54763. _this.useVertexColor = useVertexColor;
  54764. _this.useVertexAlpha = useVertexAlpha;
  54765. _this.color = new BABYLON.Color3(1, 1, 1);
  54766. _this.alpha = 1;
  54767. if (source) {
  54768. _this.color = source.color.clone();
  54769. _this.alpha = source.alpha;
  54770. _this.useVertexColor = source.useVertexColor;
  54771. _this.useVertexAlpha = source.useVertexAlpha;
  54772. }
  54773. _this._intersectionThreshold = 0.1;
  54774. var defines = [];
  54775. var options = {
  54776. attributes: [BABYLON.VertexBuffer.PositionKind],
  54777. uniforms: ["world", "viewProjection"],
  54778. needAlphaBlending: true,
  54779. defines: defines
  54780. };
  54781. if (useVertexAlpha === false) {
  54782. options.needAlphaBlending = false;
  54783. }
  54784. if (!useVertexColor) {
  54785. options.uniforms.push("color");
  54786. }
  54787. else {
  54788. options.defines.push("#define VERTEXCOLOR");
  54789. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  54790. }
  54791. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  54792. return _this;
  54793. }
  54794. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  54795. /**
  54796. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54797. * This margin is expressed in world space coordinates, so its value may vary.
  54798. * Default value is 0.1
  54799. * @returns the intersection Threshold value.
  54800. */
  54801. get: function () {
  54802. return this._intersectionThreshold;
  54803. },
  54804. /**
  54805. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54806. * This margin is expressed in world space coordinates, so its value may vary.
  54807. * @param value the new threshold to apply
  54808. */
  54809. set: function (value) {
  54810. if (this._intersectionThreshold === value) {
  54811. return;
  54812. }
  54813. this._intersectionThreshold = value;
  54814. if (this.geometry) {
  54815. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  54816. }
  54817. },
  54818. enumerable: true,
  54819. configurable: true
  54820. });
  54821. /**
  54822. * Returns the string "LineMesh"
  54823. */
  54824. LinesMesh.prototype.getClassName = function () {
  54825. return "LinesMesh";
  54826. };
  54827. Object.defineProperty(LinesMesh.prototype, "material", {
  54828. get: function () {
  54829. return this._colorShader;
  54830. },
  54831. set: function (value) {
  54832. // Do nothing
  54833. },
  54834. enumerable: true,
  54835. configurable: true
  54836. });
  54837. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  54838. get: function () {
  54839. return false;
  54840. },
  54841. enumerable: true,
  54842. configurable: true
  54843. });
  54844. LinesMesh.prototype.createInstance = function (name) {
  54845. throw new Error("LinesMeshes do not support createInstance.");
  54846. };
  54847. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  54848. if (!this._geometry) {
  54849. return this;
  54850. }
  54851. // VBOs
  54852. this._geometry._bind(this._colorShader.getEffect());
  54853. // Color
  54854. if (!this.useVertexColor) {
  54855. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  54856. }
  54857. return this;
  54858. };
  54859. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  54860. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  54861. return this;
  54862. }
  54863. var engine = this.getScene().getEngine();
  54864. // Draw order
  54865. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  54866. return this;
  54867. };
  54868. LinesMesh.prototype.dispose = function (doNotRecurse) {
  54869. this._colorShader.dispose();
  54870. _super.prototype.dispose.call(this, doNotRecurse);
  54871. };
  54872. /**
  54873. * Returns a new LineMesh object cloned from the current one.
  54874. */
  54875. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54876. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  54877. };
  54878. return LinesMesh;
  54879. }(BABYLON.Mesh));
  54880. BABYLON.LinesMesh = LinesMesh;
  54881. })(BABYLON || (BABYLON = {}));
  54882. //# sourceMappingURL=babylon.linesMesh.js.map
  54883. var BABYLON;
  54884. (function (BABYLON) {
  54885. var MeshBuilder = /** @class */ (function () {
  54886. function MeshBuilder() {
  54887. }
  54888. MeshBuilder.updateSideOrientation = function (orientation) {
  54889. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  54890. return BABYLON.Mesh.DOUBLESIDE;
  54891. }
  54892. if (orientation === undefined || orientation === null) {
  54893. return BABYLON.Mesh.FRONTSIDE;
  54894. }
  54895. return orientation;
  54896. };
  54897. /**
  54898. * Creates a box mesh.
  54899. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  54900. * The parameter `size` sets the size (float) of each box side (default 1).
  54901. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  54902. * 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).
  54903. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54904. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54905. * 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).
  54906. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54907. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54908. */
  54909. MeshBuilder.CreateBox = function (name, options, scene) {
  54910. if (scene === void 0) { scene = null; }
  54911. var box = new BABYLON.Mesh(name, scene);
  54912. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54913. box._originalBuilderSideOrientation = options.sideOrientation;
  54914. var vertexData = BABYLON.VertexData.CreateBox(options);
  54915. vertexData.applyToMesh(box, options.updatable);
  54916. return box;
  54917. };
  54918. /**
  54919. * Creates a sphere mesh.
  54920. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  54921. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  54922. * 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`).
  54923. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  54924. * 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
  54925. * 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).
  54926. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54927. * 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).
  54928. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54929. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54930. */
  54931. MeshBuilder.CreateSphere = function (name, options, scene) {
  54932. var sphere = new BABYLON.Mesh(name, scene);
  54933. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54934. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54935. var vertexData = BABYLON.VertexData.CreateSphere(options);
  54936. vertexData.applyToMesh(sphere, options.updatable);
  54937. return sphere;
  54938. };
  54939. /**
  54940. * Creates a plane polygonal mesh. By default, this is a disc.
  54941. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  54942. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  54943. * 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.
  54944. * 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
  54945. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54946. * 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).
  54947. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54948. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54949. */
  54950. MeshBuilder.CreateDisc = function (name, options, scene) {
  54951. if (scene === void 0) { scene = null; }
  54952. var disc = new BABYLON.Mesh(name, scene);
  54953. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54954. disc._originalBuilderSideOrientation = options.sideOrientation;
  54955. var vertexData = BABYLON.VertexData.CreateDisc(options);
  54956. vertexData.applyToMesh(disc, options.updatable);
  54957. return disc;
  54958. };
  54959. /**
  54960. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  54961. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  54962. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  54963. * 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`).
  54964. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  54965. * 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.
  54966. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54967. * 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).
  54968. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54969. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54970. */
  54971. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  54972. var sphere = new BABYLON.Mesh(name, scene);
  54973. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54974. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54975. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  54976. vertexData.applyToMesh(sphere, options.updatable);
  54977. return sphere;
  54978. };
  54979. ;
  54980. /**
  54981. * Creates a ribbon mesh.
  54982. * 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.
  54983. *
  54984. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  54985. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  54986. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  54987. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  54988. * 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.
  54989. * 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.
  54990. * 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
  54991. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54992. * 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).
  54993. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54994. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54995. * 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.
  54996. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  54997. * 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
  54998. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  54999. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  55000. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55001. */
  55002. MeshBuilder.CreateRibbon = function (name, options, scene) {
  55003. if (scene === void 0) { scene = null; }
  55004. var pathArray = options.pathArray;
  55005. var closeArray = options.closeArray;
  55006. var closePath = options.closePath;
  55007. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55008. var instance = options.instance;
  55009. var updatable = options.updatable;
  55010. if (instance) {
  55011. // positionFunction : ribbon case
  55012. // only pathArray and sideOrientation parameters are taken into account for positions update
  55013. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  55014. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  55015. var positionFunction = function (positions) {
  55016. var minlg = pathArray[0].length;
  55017. var i = 0;
  55018. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  55019. for (var si = 1; si <= ns; si++) {
  55020. for (var p = 0; p < pathArray.length; p++) {
  55021. var path = pathArray[p];
  55022. var l = path.length;
  55023. minlg = (minlg < l) ? minlg : l;
  55024. var j = 0;
  55025. while (j < minlg) {
  55026. positions[i] = path[j].x;
  55027. positions[i + 1] = path[j].y;
  55028. positions[i + 2] = path[j].z;
  55029. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  55030. BABYLON.Tmp.Vector3[0].x = path[j].x;
  55031. }
  55032. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  55033. BABYLON.Tmp.Vector3[1].x = path[j].x;
  55034. }
  55035. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  55036. BABYLON.Tmp.Vector3[0].y = path[j].y;
  55037. }
  55038. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  55039. BABYLON.Tmp.Vector3[1].y = path[j].y;
  55040. }
  55041. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  55042. BABYLON.Tmp.Vector3[0].z = path[j].z;
  55043. }
  55044. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  55045. BABYLON.Tmp.Vector3[1].z = path[j].z;
  55046. }
  55047. j++;
  55048. i += 3;
  55049. }
  55050. if (instance._closePath) {
  55051. positions[i] = path[0].x;
  55052. positions[i + 1] = path[0].y;
  55053. positions[i + 2] = path[0].z;
  55054. i += 3;
  55055. }
  55056. }
  55057. }
  55058. };
  55059. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55060. positionFunction(positions);
  55061. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55062. instance._boundingInfo.update(instance._worldMatrix);
  55063. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55064. if (options.colors) {
  55065. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55066. for (var c = 0; c < options.colors.length; c++) {
  55067. colors[c * 4] = options.colors[c].r;
  55068. colors[c * 4 + 1] = options.colors[c].g;
  55069. colors[c * 4 + 2] = options.colors[c].b;
  55070. colors[c * 4 + 3] = options.colors[c].a;
  55071. }
  55072. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55073. }
  55074. if (options.uvs) {
  55075. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55076. for (var i = 0; i < options.uvs.length; i++) {
  55077. uvs[i * 2] = options.uvs[i].x;
  55078. uvs[i * 2 + 1] = options.uvs[i].y;
  55079. }
  55080. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55081. }
  55082. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55083. var indices = instance.getIndices();
  55084. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55085. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55086. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55087. if (instance._closePath) {
  55088. var indexFirst = 0;
  55089. var indexLast = 0;
  55090. for (var p = 0; p < pathArray.length; p++) {
  55091. indexFirst = instance._idx[p] * 3;
  55092. if (p + 1 < pathArray.length) {
  55093. indexLast = (instance._idx[p + 1] - 1) * 3;
  55094. }
  55095. else {
  55096. indexLast = normals.length - 3;
  55097. }
  55098. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55099. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55100. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55101. normals[indexLast] = normals[indexFirst];
  55102. normals[indexLast + 1] = normals[indexFirst + 1];
  55103. normals[indexLast + 2] = normals[indexFirst + 2];
  55104. }
  55105. }
  55106. if (!(instance.areNormalsFrozen)) {
  55107. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55108. }
  55109. }
  55110. return instance;
  55111. }
  55112. else {
  55113. var ribbon = new BABYLON.Mesh(name, scene);
  55114. ribbon._originalBuilderSideOrientation = sideOrientation;
  55115. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55116. if (closePath) {
  55117. ribbon._idx = vertexData._idx;
  55118. }
  55119. ribbon._closePath = closePath;
  55120. ribbon._closeArray = closeArray;
  55121. vertexData.applyToMesh(ribbon, updatable);
  55122. return ribbon;
  55123. }
  55124. };
  55125. /**
  55126. * Creates a cylinder or a cone mesh.
  55127. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55128. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55129. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55130. * 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.
  55131. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55132. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55133. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55134. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55135. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55136. * 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).
  55137. * 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
  55138. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55139. * 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
  55140. * 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.
  55141. * If `enclose` is false, a ring surface is one element.
  55142. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55143. * 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
  55144. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55145. * 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).
  55146. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55147. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55148. */
  55149. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55150. var cylinder = new BABYLON.Mesh(name, scene);
  55151. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55152. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55153. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55154. vertexData.applyToMesh(cylinder, options.updatable);
  55155. return cylinder;
  55156. };
  55157. /**
  55158. * Creates a torus mesh.
  55159. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55160. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55161. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55162. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55163. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55164. * 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).
  55165. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55166. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55167. */
  55168. MeshBuilder.CreateTorus = function (name, options, scene) {
  55169. var torus = new BABYLON.Mesh(name, scene);
  55170. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55171. torus._originalBuilderSideOrientation = options.sideOrientation;
  55172. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55173. vertexData.applyToMesh(torus, options.updatable);
  55174. return torus;
  55175. };
  55176. /**
  55177. * Creates a torus knot mesh.
  55178. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55179. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55180. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55181. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55182. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55183. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55184. * 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).
  55185. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55186. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55187. */
  55188. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  55189. var torusKnot = new BABYLON.Mesh(name, scene);
  55190. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55191. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55192. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55193. vertexData.applyToMesh(torusKnot, options.updatable);
  55194. return torusKnot;
  55195. };
  55196. /**
  55197. * Creates a line system mesh.
  55198. * A line system is a pool of many lines gathered in a single mesh.
  55199. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55200. * 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.
  55201. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55202. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55203. * 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
  55204. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55205. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55206. * 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
  55207. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55208. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55209. */
  55210. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55211. var instance = options.instance;
  55212. var lines = options.lines;
  55213. var colors = options.colors;
  55214. if (instance) {
  55215. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55216. var vertexColor;
  55217. var lineColors;
  55218. if (colors) {
  55219. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55220. }
  55221. var i = 0;
  55222. var c = 0;
  55223. for (var l = 0; l < lines.length; l++) {
  55224. var points = lines[l];
  55225. for (var p = 0; p < points.length; p++) {
  55226. positions[i] = points[p].x;
  55227. positions[i + 1] = points[p].y;
  55228. positions[i + 2] = points[p].z;
  55229. if (colors && vertexColor) {
  55230. lineColors = colors[l];
  55231. vertexColor[c] = lineColors[p].r;
  55232. vertexColor[c + 1] = lineColors[p].g;
  55233. vertexColor[c + 2] = lineColors[p].b;
  55234. vertexColor[c + 3] = lineColors[p].a;
  55235. c += 4;
  55236. }
  55237. i += 3;
  55238. }
  55239. }
  55240. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55241. if (colors && vertexColor) {
  55242. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  55243. }
  55244. return instance;
  55245. }
  55246. // line system creation
  55247. var useVertexColor = (colors) ? true : false;
  55248. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  55249. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  55250. vertexData.applyToMesh(lineSystem, options.updatable);
  55251. return lineSystem;
  55252. };
  55253. /**
  55254. * Creates a line mesh.
  55255. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55256. * 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.
  55257. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55258. * The parameter `points` is an array successive Vector3.
  55259. * 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
  55260. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55261. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55262. * When updating an instance, remember that only point positions can change, not the number of points.
  55263. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55264. */
  55265. MeshBuilder.CreateLines = function (name, options, scene) {
  55266. if (scene === void 0) { scene = null; }
  55267. var colors = (options.colors) ? [options.colors] : null;
  55268. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55269. return lines;
  55270. };
  55271. /**
  55272. * Creates a dashed line mesh.
  55273. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55274. * 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.
  55275. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55276. * The parameter `points` is an array successive Vector3.
  55277. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55278. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55279. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55280. * 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
  55281. * When updating an instance, remember that only point positions can change, not the number of points.
  55282. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55283. */
  55284. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55285. if (scene === void 0) { scene = null; }
  55286. var points = options.points;
  55287. var instance = options.instance;
  55288. var gapSize = options.gapSize || 1;
  55289. var dashSize = options.dashSize || 3;
  55290. if (instance) {
  55291. var positionFunction = function (positions) {
  55292. var curvect = BABYLON.Vector3.Zero();
  55293. var nbSeg = positions.length / 6;
  55294. var lg = 0;
  55295. var nb = 0;
  55296. var shft = 0;
  55297. var dashshft = 0;
  55298. var curshft = 0;
  55299. var p = 0;
  55300. var i = 0;
  55301. var j = 0;
  55302. for (i = 0; i < points.length - 1; i++) {
  55303. points[i + 1].subtractToRef(points[i], curvect);
  55304. lg += curvect.length();
  55305. }
  55306. shft = lg / nbSeg;
  55307. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55308. for (i = 0; i < points.length - 1; i++) {
  55309. points[i + 1].subtractToRef(points[i], curvect);
  55310. nb = Math.floor(curvect.length() / shft);
  55311. curvect.normalize();
  55312. j = 0;
  55313. while (j < nb && p < positions.length) {
  55314. curshft = shft * j;
  55315. positions[p] = points[i].x + curshft * curvect.x;
  55316. positions[p + 1] = points[i].y + curshft * curvect.y;
  55317. positions[p + 2] = points[i].z + curshft * curvect.z;
  55318. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  55319. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  55320. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  55321. p += 6;
  55322. j++;
  55323. }
  55324. }
  55325. while (p < positions.length) {
  55326. positions[p] = points[i].x;
  55327. positions[p + 1] = points[i].y;
  55328. positions[p + 2] = points[i].z;
  55329. p += 3;
  55330. }
  55331. };
  55332. instance.updateMeshPositions(positionFunction, false);
  55333. return instance;
  55334. }
  55335. // dashed lines creation
  55336. var dashedLines = new BABYLON.LinesMesh(name, scene);
  55337. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  55338. vertexData.applyToMesh(dashedLines, options.updatable);
  55339. dashedLines.dashSize = dashSize;
  55340. dashedLines.gapSize = gapSize;
  55341. return dashedLines;
  55342. };
  55343. /**
  55344. * Creates an extruded shape mesh.
  55345. * 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.
  55346. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  55347. *
  55348. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55349. * 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
  55350. * extruded along the Z axis.
  55351. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55352. * 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.
  55353. * The parameter `scale` (float, default 1) is the value to scale the shape.
  55354. * 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
  55355. * 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
  55356. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55357. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55358. * 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).
  55359. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55360. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55361. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55362. */
  55363. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  55364. if (scene === void 0) { scene = null; }
  55365. var path = options.path;
  55366. var shape = options.shape;
  55367. var scale = options.scale || 1;
  55368. var rotation = options.rotation || 0;
  55369. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55370. var updatable = options.updatable;
  55371. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55372. var instance = options.instance || null;
  55373. var invertUV = options.invertUV || false;
  55374. 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);
  55375. };
  55376. /**
  55377. * Creates an custom extruded shape mesh.
  55378. * 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.
  55379. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  55380. *
  55381. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55382. * 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
  55383. * extruded along the Z axis.
  55384. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55385. * 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
  55386. * and the distance of this point from the begining of the path :
  55387. * ```javascript
  55388. * var rotationFunction = function(i, distance) {
  55389. * // do things
  55390. * return rotationValue; }
  55391. * ```
  55392. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  55393. * 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
  55394. * and the distance of this point from the begining of the path :
  55395. * ```javascript
  55396. * var scaleFunction = function(i, distance) {
  55397. * // do things
  55398. * return scaleValue;}
  55399. * ```
  55400. * It must returns a float value that will be the scale value applied to the shape on each path point.
  55401. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  55402. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  55403. * 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
  55404. * 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
  55405. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55406. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55407. * 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).
  55408. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55409. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55410. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55411. */
  55412. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  55413. var path = options.path;
  55414. var shape = options.shape;
  55415. var scaleFunction = options.scaleFunction || (function () { return 1; });
  55416. var rotationFunction = options.rotationFunction || (function () { return 0; });
  55417. var ribbonCloseArray = options.ribbonCloseArray || false;
  55418. var ribbonClosePath = options.ribbonClosePath || false;
  55419. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55420. var updatable = options.updatable;
  55421. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55422. var instance = options.instance;
  55423. var invertUV = options.invertUV || false;
  55424. 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);
  55425. };
  55426. /**
  55427. * Creates lathe mesh.
  55428. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  55429. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  55430. *
  55431. * 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
  55432. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  55433. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  55434. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  55435. * 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.
  55436. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  55437. * 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
  55438. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55439. * 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).
  55440. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55441. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55443. */
  55444. MeshBuilder.CreateLathe = function (name, options, scene) {
  55445. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  55446. var closed = (options.closed === undefined) ? true : options.closed;
  55447. var shape = options.shape;
  55448. var radius = options.radius || 1;
  55449. var tessellation = options.tessellation || 64;
  55450. var updatable = options.updatable;
  55451. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55452. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55453. var pi2 = Math.PI * 2;
  55454. var paths = new Array();
  55455. var invertUV = options.invertUV || false;
  55456. var i = 0;
  55457. var p = 0;
  55458. var step = pi2 / tessellation * arc;
  55459. var rotated;
  55460. var path = new Array();
  55461. ;
  55462. for (i = 0; i <= tessellation; i++) {
  55463. var path = [];
  55464. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  55465. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  55466. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  55467. }
  55468. for (p = 0; p < shape.length; p++) {
  55469. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  55470. path.push(rotated);
  55471. }
  55472. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  55473. 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));
  55474. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  55475. }
  55476. paths.push(path);
  55477. }
  55478. // lathe ribbon
  55479. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55480. return lathe;
  55481. };
  55482. /**
  55483. * Creates a plane mesh.
  55484. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55485. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  55486. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  55487. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  55488. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55489. * 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).
  55490. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55491. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55492. */
  55493. MeshBuilder.CreatePlane = function (name, options, scene) {
  55494. var plane = new BABYLON.Mesh(name, scene);
  55495. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55496. plane._originalBuilderSideOrientation = options.sideOrientation;
  55497. var vertexData = BABYLON.VertexData.CreatePlane(options);
  55498. vertexData.applyToMesh(plane, options.updatable);
  55499. if (options.sourcePlane) {
  55500. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  55501. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  55502. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  55503. plane.rotate(vectorProduct, product);
  55504. }
  55505. return plane;
  55506. };
  55507. /**
  55508. * Creates a ground mesh.
  55509. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55510. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  55511. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  55512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55513. */
  55514. MeshBuilder.CreateGround = function (name, options, scene) {
  55515. var ground = new BABYLON.GroundMesh(name, scene);
  55516. ground._setReady(false);
  55517. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  55518. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  55519. ground._width = options.width || 1;
  55520. ground._height = options.height || 1;
  55521. ground._maxX = ground._width / 2;
  55522. ground._maxZ = ground._height / 2;
  55523. ground._minX = -ground._maxX;
  55524. ground._minZ = -ground._maxZ;
  55525. var vertexData = BABYLON.VertexData.CreateGround(options);
  55526. vertexData.applyToMesh(ground, options.updatable);
  55527. ground._setReady(true);
  55528. return ground;
  55529. };
  55530. /**
  55531. * Creates a tiled ground mesh.
  55532. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  55533. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  55534. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  55535. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  55536. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  55537. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  55538. * numbers of subdivisions on the ground width and height of each tile.
  55539. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55540. */
  55541. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  55542. var tiledGround = new BABYLON.Mesh(name, scene);
  55543. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  55544. vertexData.applyToMesh(tiledGround, options.updatable);
  55545. return tiledGround;
  55546. };
  55547. /**
  55548. * Creates a ground mesh from a height map.
  55549. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  55550. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  55551. * The parameter `url` sets the URL of the height map image resource.
  55552. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  55553. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  55554. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  55555. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  55556. * 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.
  55557. * 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).
  55558. * This function is passed the newly built mesh :
  55559. * ```javascript
  55560. * function(mesh) { // do things
  55561. * return; }
  55562. * ```
  55563. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55564. */
  55565. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  55566. var width = options.width || 10.0;
  55567. var height = options.height || 10.0;
  55568. var subdivisions = options.subdivisions || 1 | 0;
  55569. var minHeight = options.minHeight || 0.0;
  55570. var maxHeight = options.maxHeight || 1.0;
  55571. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  55572. var updatable = options.updatable;
  55573. var onReady = options.onReady;
  55574. var ground = new BABYLON.GroundMesh(name, scene);
  55575. ground._subdivisionsX = subdivisions;
  55576. ground._subdivisionsY = subdivisions;
  55577. ground._width = width;
  55578. ground._height = height;
  55579. ground._maxX = ground._width / 2.0;
  55580. ground._maxZ = ground._height / 2.0;
  55581. ground._minX = -ground._maxX;
  55582. ground._minZ = -ground._maxZ;
  55583. ground._setReady(false);
  55584. var onload = function (img) {
  55585. // Getting height map data
  55586. var canvas = document.createElement("canvas");
  55587. var context = canvas.getContext("2d");
  55588. if (!context) {
  55589. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  55590. }
  55591. if (scene.isDisposed) {
  55592. return;
  55593. }
  55594. var bufferWidth = img.width;
  55595. var bufferHeight = img.height;
  55596. canvas.width = bufferWidth;
  55597. canvas.height = bufferHeight;
  55598. context.drawImage(img, 0, 0);
  55599. // Create VertexData from map data
  55600. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  55601. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  55602. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  55603. width: width, height: height,
  55604. subdivisions: subdivisions,
  55605. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  55606. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  55607. });
  55608. vertexData.applyToMesh(ground, updatable);
  55609. ground._setReady(true);
  55610. //execute ready callback, if set
  55611. if (onReady) {
  55612. onReady(ground);
  55613. }
  55614. };
  55615. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  55616. return ground;
  55617. };
  55618. /**
  55619. * Creates a polygon mesh.
  55620. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  55621. * 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.
  55622. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55623. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55624. * 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).
  55625. * Remember you can only change the shape positions, not their number when updating a polygon.
  55626. */
  55627. MeshBuilder.CreatePolygon = function (name, options, scene) {
  55628. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55629. var shape = options.shape;
  55630. var holes = options.holes || [];
  55631. var depth = options.depth || 0;
  55632. var contours = [];
  55633. var hole = [];
  55634. for (var i = 0; i < shape.length; i++) {
  55635. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  55636. }
  55637. var epsilon = 0.00000001;
  55638. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  55639. contours.pop();
  55640. }
  55641. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  55642. for (var hNb = 0; hNb < holes.length; hNb++) {
  55643. hole = [];
  55644. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  55645. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  55646. }
  55647. polygonTriangulation.addHole(hole);
  55648. }
  55649. var polygon = polygonTriangulation.build(options.updatable, depth);
  55650. polygon._originalBuilderSideOrientation = options.sideOrientation;
  55651. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  55652. vertexData.applyToMesh(polygon, options.updatable);
  55653. return polygon;
  55654. };
  55655. ;
  55656. /**
  55657. * Creates an extruded polygon mesh, with depth in the Y direction.
  55658. * 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).
  55659. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55660. */
  55661. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  55662. return MeshBuilder.CreatePolygon(name, options, scene);
  55663. };
  55664. ;
  55665. /**
  55666. * Creates a tube mesh.
  55667. * 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.
  55668. *
  55669. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  55670. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  55671. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  55672. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  55673. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  55674. * 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.
  55675. * It must return a radius value (positive float) :
  55676. * ```javascript
  55677. * var radiusFunction = function(i, distance) {
  55678. * // do things
  55679. * return radius; }
  55680. * ```
  55681. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  55682. * 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
  55683. * 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
  55684. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55685. * 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).
  55686. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55687. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55688. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55689. */
  55690. MeshBuilder.CreateTube = function (name, options, scene) {
  55691. var path = options.path;
  55692. var instance = options.instance;
  55693. var radius = 1.0;
  55694. if (instance) {
  55695. radius = instance.radius;
  55696. }
  55697. if (options.radius !== undefined) {
  55698. radius = options.radius;
  55699. }
  55700. ;
  55701. var tessellation = options.tessellation || 64 | 0;
  55702. var radiusFunction = options.radiusFunction || null;
  55703. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55704. var invertUV = options.invertUV || false;
  55705. var updatable = options.updatable;
  55706. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55707. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  55708. // tube geometry
  55709. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  55710. var tangents = path3D.getTangents();
  55711. var normals = path3D.getNormals();
  55712. var distances = path3D.getDistances();
  55713. var pi2 = Math.PI * 2;
  55714. var step = pi2 / tessellation * arc;
  55715. var returnRadius = function () { return radius; };
  55716. var radiusFunctionFinal = radiusFunction || returnRadius;
  55717. var circlePath;
  55718. var rad;
  55719. var normal;
  55720. var rotated;
  55721. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55722. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55723. for (var i = 0; i < path.length; i++) {
  55724. rad = radiusFunctionFinal(i, distances[i]); // current radius
  55725. circlePath = Array(); // current circle array
  55726. normal = normals[i]; // current normal
  55727. for (var t = 0; t < tessellation; t++) {
  55728. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  55729. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  55730. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  55731. rotated.scaleInPlace(rad).addInPlace(path[i]);
  55732. circlePath[t] = rotated;
  55733. }
  55734. circlePaths[index] = circlePath;
  55735. index++;
  55736. }
  55737. // cap
  55738. var capPath = function (nbPoints, pathIndex) {
  55739. var pointCap = Array();
  55740. for (var i = 0; i < nbPoints; i++) {
  55741. pointCap.push(path[pathIndex]);
  55742. }
  55743. return pointCap;
  55744. };
  55745. switch (cap) {
  55746. case BABYLON.Mesh.NO_CAP:
  55747. break;
  55748. case BABYLON.Mesh.CAP_START:
  55749. circlePaths[0] = capPath(tessellation, 0);
  55750. circlePaths[1] = circlePaths[2].slice(0);
  55751. break;
  55752. case BABYLON.Mesh.CAP_END:
  55753. circlePaths[index] = circlePaths[index - 1].slice(0);
  55754. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55755. break;
  55756. case BABYLON.Mesh.CAP_ALL:
  55757. circlePaths[0] = capPath(tessellation, 0);
  55758. circlePaths[1] = circlePaths[2].slice(0);
  55759. circlePaths[index] = circlePaths[index - 1].slice(0);
  55760. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55761. break;
  55762. default:
  55763. break;
  55764. }
  55765. return circlePaths;
  55766. };
  55767. var path3D;
  55768. var pathArray;
  55769. if (instance) {
  55770. var arc = options.arc || instance.arc;
  55771. path3D = (instance.path3D).update(path);
  55772. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  55773. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  55774. instance.path3D = path3D;
  55775. instance.pathArray = pathArray;
  55776. instance.arc = arc;
  55777. instance.radius = radius;
  55778. return instance;
  55779. }
  55780. // tube creation
  55781. path3D = new BABYLON.Path3D(path);
  55782. var newPathArray = new Array();
  55783. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55784. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  55785. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55786. tube.pathArray = pathArray;
  55787. tube.path3D = path3D;
  55788. tube.tessellation = tessellation;
  55789. tube.cap = cap;
  55790. tube.arc = options.arc;
  55791. tube.radius = radius;
  55792. return tube;
  55793. };
  55794. /**
  55795. * Creates a polyhedron mesh.
  55796. *
  55797. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  55798. * 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
  55799. * to choose the wanted type.
  55800. * The parameter `size` (positive float, default 1) sets the polygon size.
  55801. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  55802. * 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`.
  55803. * 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
  55804. * 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)`).
  55805. * 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
  55806. * 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.
  55807. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55808. * 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).
  55809. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55810. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55811. */
  55812. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  55813. var polyhedron = new BABYLON.Mesh(name, scene);
  55814. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55815. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  55816. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  55817. vertexData.applyToMesh(polyhedron, options.updatable);
  55818. return polyhedron;
  55819. };
  55820. /**
  55821. * Creates a decal mesh.
  55822. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  55823. * 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.
  55824. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  55825. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  55826. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  55827. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  55828. */
  55829. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  55830. var indices = sourceMesh.getIndices();
  55831. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55832. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55833. var position = options.position || BABYLON.Vector3.Zero();
  55834. var normal = options.normal || BABYLON.Vector3.Up();
  55835. var size = options.size || BABYLON.Vector3.One();
  55836. var angle = options.angle || 0;
  55837. // Getting correct rotation
  55838. if (!normal) {
  55839. var target = new BABYLON.Vector3(0, 0, 1);
  55840. var camera = sourceMesh.getScene().activeCamera;
  55841. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  55842. normal = camera.globalPosition.subtract(cameraWorldTarget);
  55843. }
  55844. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  55845. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  55846. var pitch = Math.atan2(normal.y, len);
  55847. // Matrix
  55848. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  55849. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  55850. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  55851. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  55852. var vertexData = new BABYLON.VertexData();
  55853. vertexData.indices = [];
  55854. vertexData.positions = [];
  55855. vertexData.normals = [];
  55856. vertexData.uvs = [];
  55857. var currentVertexDataIndex = 0;
  55858. var extractDecalVector3 = function (indexId) {
  55859. var result = new BABYLON.PositionNormalVertex();
  55860. if (!indices || !positions || !normals) {
  55861. return result;
  55862. }
  55863. var vertexId = indices[indexId];
  55864. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  55865. // Send vector to decal local world
  55866. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  55867. // Get normal
  55868. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  55869. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  55870. return result;
  55871. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  55872. var clip = function (vertices, axis) {
  55873. if (vertices.length === 0) {
  55874. return vertices;
  55875. }
  55876. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  55877. var clipVertices = function (v0, v1) {
  55878. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  55879. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  55880. };
  55881. var result = new Array();
  55882. for (var index = 0; index < vertices.length; index += 3) {
  55883. var v1Out;
  55884. var v2Out;
  55885. var v3Out;
  55886. var total = 0;
  55887. var nV1 = null;
  55888. var nV2 = null;
  55889. var nV3 = null;
  55890. var nV4 = null;
  55891. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  55892. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  55893. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  55894. v1Out = d1 > 0;
  55895. v2Out = d2 > 0;
  55896. v3Out = d3 > 0;
  55897. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  55898. switch (total) {
  55899. case 0:
  55900. result.push(vertices[index]);
  55901. result.push(vertices[index + 1]);
  55902. result.push(vertices[index + 2]);
  55903. break;
  55904. case 1:
  55905. if (v1Out) {
  55906. nV1 = vertices[index + 1];
  55907. nV2 = vertices[index + 2];
  55908. nV3 = clipVertices(vertices[index], nV1);
  55909. nV4 = clipVertices(vertices[index], nV2);
  55910. }
  55911. if (v2Out) {
  55912. nV1 = vertices[index];
  55913. nV2 = vertices[index + 2];
  55914. nV3 = clipVertices(vertices[index + 1], nV1);
  55915. nV4 = clipVertices(vertices[index + 1], nV2);
  55916. result.push(nV3);
  55917. result.push(nV2.clone());
  55918. result.push(nV1.clone());
  55919. result.push(nV2.clone());
  55920. result.push(nV3.clone());
  55921. result.push(nV4);
  55922. break;
  55923. }
  55924. if (v3Out) {
  55925. nV1 = vertices[index];
  55926. nV2 = vertices[index + 1];
  55927. nV3 = clipVertices(vertices[index + 2], nV1);
  55928. nV4 = clipVertices(vertices[index + 2], nV2);
  55929. }
  55930. if (nV1 && nV2 && nV3 && nV4) {
  55931. result.push(nV1.clone());
  55932. result.push(nV2.clone());
  55933. result.push(nV3);
  55934. result.push(nV4);
  55935. result.push(nV3.clone());
  55936. result.push(nV2.clone());
  55937. }
  55938. break;
  55939. case 2:
  55940. if (!v1Out) {
  55941. nV1 = vertices[index].clone();
  55942. nV2 = clipVertices(nV1, vertices[index + 1]);
  55943. nV3 = clipVertices(nV1, vertices[index + 2]);
  55944. result.push(nV1);
  55945. result.push(nV2);
  55946. result.push(nV3);
  55947. }
  55948. if (!v2Out) {
  55949. nV1 = vertices[index + 1].clone();
  55950. nV2 = clipVertices(nV1, vertices[index + 2]);
  55951. nV3 = clipVertices(nV1, vertices[index]);
  55952. result.push(nV1);
  55953. result.push(nV2);
  55954. result.push(nV3);
  55955. }
  55956. if (!v3Out) {
  55957. nV1 = vertices[index + 2].clone();
  55958. nV2 = clipVertices(nV1, vertices[index]);
  55959. nV3 = clipVertices(nV1, vertices[index + 1]);
  55960. result.push(nV1);
  55961. result.push(nV2);
  55962. result.push(nV3);
  55963. }
  55964. break;
  55965. case 3:
  55966. break;
  55967. }
  55968. }
  55969. return result;
  55970. };
  55971. for (var index = 0; index < indices.length; index += 3) {
  55972. var faceVertices = new Array();
  55973. faceVertices.push(extractDecalVector3(index));
  55974. faceVertices.push(extractDecalVector3(index + 1));
  55975. faceVertices.push(extractDecalVector3(index + 2));
  55976. // Clip
  55977. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  55978. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  55979. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  55980. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  55981. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  55982. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  55983. if (faceVertices.length === 0) {
  55984. continue;
  55985. }
  55986. // Add UVs and get back to world
  55987. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  55988. var vertex = faceVertices[vIndex];
  55989. //TODO check for Int32Array | Uint32Array | Uint16Array
  55990. vertexData.indices.push(currentVertexDataIndex);
  55991. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  55992. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  55993. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  55994. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  55995. currentVertexDataIndex++;
  55996. }
  55997. }
  55998. // Return mesh
  55999. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  56000. vertexData.applyToMesh(decal);
  56001. decal.position = position.clone();
  56002. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  56003. return decal;
  56004. };
  56005. // Privates
  56006. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  56007. // extrusion geometry
  56008. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  56009. var tangents = path3D.getTangents();
  56010. var normals = path3D.getNormals();
  56011. var binormals = path3D.getBinormals();
  56012. var distances = path3D.getDistances();
  56013. var angle = 0;
  56014. var returnScale = function () { return scale !== null ? scale : 1; };
  56015. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  56016. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  56017. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  56018. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56019. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56020. for (var i = 0; i < curve.length; i++) {
  56021. var shapePath = new Array();
  56022. var angleStep = rotate(i, distances[i]);
  56023. var scaleRatio = scl(i, distances[i]);
  56024. for (var p = 0; p < shape.length; p++) {
  56025. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  56026. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  56027. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  56028. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  56029. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  56030. shapePath[p] = rotated;
  56031. }
  56032. shapePaths[index] = shapePath;
  56033. angle += angleStep;
  56034. index++;
  56035. }
  56036. // cap
  56037. var capPath = function (shapePath) {
  56038. var pointCap = Array();
  56039. var barycenter = BABYLON.Vector3.Zero();
  56040. var i;
  56041. for (i = 0; i < shapePath.length; i++) {
  56042. barycenter.addInPlace(shapePath[i]);
  56043. }
  56044. barycenter.scaleInPlace(1.0 / shapePath.length);
  56045. for (i = 0; i < shapePath.length; i++) {
  56046. pointCap.push(barycenter);
  56047. }
  56048. return pointCap;
  56049. };
  56050. switch (cap) {
  56051. case BABYLON.Mesh.NO_CAP:
  56052. break;
  56053. case BABYLON.Mesh.CAP_START:
  56054. shapePaths[0] = capPath(shapePaths[2]);
  56055. shapePaths[1] = shapePaths[2];
  56056. break;
  56057. case BABYLON.Mesh.CAP_END:
  56058. shapePaths[index] = shapePaths[index - 1];
  56059. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56060. break;
  56061. case BABYLON.Mesh.CAP_ALL:
  56062. shapePaths[0] = capPath(shapePaths[2]);
  56063. shapePaths[1] = shapePaths[2];
  56064. shapePaths[index] = shapePaths[index - 1];
  56065. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56066. break;
  56067. default:
  56068. break;
  56069. }
  56070. return shapePaths;
  56071. };
  56072. var path3D;
  56073. var pathArray;
  56074. if (instance) {
  56075. path3D = (instance.path3D).update(curve);
  56076. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56077. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56078. return instance;
  56079. }
  56080. // extruded shape creation
  56081. path3D = new BABYLON.Path3D(curve);
  56082. var newShapePaths = new Array();
  56083. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56084. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56085. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56086. extrudedGeneric.pathArray = pathArray;
  56087. extrudedGeneric.path3D = path3D;
  56088. extrudedGeneric.cap = cap;
  56089. return extrudedGeneric;
  56090. };
  56091. return MeshBuilder;
  56092. }());
  56093. BABYLON.MeshBuilder = MeshBuilder;
  56094. })(BABYLON || (BABYLON = {}));
  56095. //# sourceMappingURL=babylon.meshBuilder.js.map
  56096. var BABYLON;
  56097. (function (BABYLON) {
  56098. /**
  56099. * Draco compression (https://google.github.io/draco/)
  56100. */
  56101. var DracoCompression = /** @class */ (function () {
  56102. /**
  56103. * Constructor
  56104. * @param numWorkers The number of workers for async operations
  56105. */
  56106. function DracoCompression(numWorkers) {
  56107. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  56108. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  56109. if (!workerBlobUrl || !Worker) {
  56110. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  56111. return;
  56112. }
  56113. var workers = new Array(numWorkers);
  56114. for (var i = 0; i < workers.length; i++) {
  56115. var worker = new Worker(workerBlobUrl);
  56116. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  56117. workers[i] = worker;
  56118. }
  56119. this._workerPool = new BABYLON.WorkerPool(workers);
  56120. }
  56121. /**
  56122. * Stop all async operations and release resources.
  56123. */
  56124. DracoCompression.prototype.dispose = function () {
  56125. this._workerPool.dispose();
  56126. delete this._workerPool;
  56127. };
  56128. /**
  56129. * Decode Draco compressed mesh data to vertex data.
  56130. * @param data The array buffer view for the Draco compression data
  56131. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56132. * @returns A promise that resolves with the decoded vertex data
  56133. */
  56134. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  56135. var _this = this;
  56136. return new Promise(function (resolve, reject) {
  56137. _this._workerPool.push(function (worker, onComplete) {
  56138. var vertexData = new BABYLON.VertexData();
  56139. var onError = function (error) {
  56140. worker.removeEventListener("error", onError);
  56141. worker.removeEventListener("message", onMessage);
  56142. reject(error);
  56143. onComplete();
  56144. };
  56145. var onMessage = function (message) {
  56146. if (message.data === "done") {
  56147. worker.removeEventListener("error", onError);
  56148. worker.removeEventListener("message", onMessage);
  56149. resolve(vertexData);
  56150. onComplete();
  56151. }
  56152. else if (message.data.id === "indices") {
  56153. vertexData.indices = message.data.value;
  56154. }
  56155. else {
  56156. vertexData.set(message.data.value, message.data.id);
  56157. }
  56158. };
  56159. worker.addEventListener("error", onError);
  56160. worker.addEventListener("message", onMessage);
  56161. var dataCopy = new Uint8Array(data.byteLength);
  56162. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  56163. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  56164. });
  56165. });
  56166. };
  56167. /**
  56168. * The worker function that gets converted to a blob url to pass into a worker.
  56169. */
  56170. DracoCompression._Worker = function () {
  56171. // self is actually a DedicatedWorkerGlobalScope
  56172. var _self = self;
  56173. var decodeMesh = function (data, attributes) {
  56174. var dracoModule = new DracoDecoderModule();
  56175. var buffer = new dracoModule.DecoderBuffer();
  56176. buffer.Init(data, data.byteLength);
  56177. var decoder = new dracoModule.Decoder();
  56178. var geometry;
  56179. var status;
  56180. try {
  56181. var type = decoder.GetEncodedGeometryType(buffer);
  56182. switch (type) {
  56183. case dracoModule.TRIANGULAR_MESH:
  56184. geometry = new dracoModule.Mesh();
  56185. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56186. break;
  56187. case dracoModule.POINT_CLOUD:
  56188. geometry = new dracoModule.PointCloud();
  56189. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  56190. break;
  56191. default:
  56192. throw new Error("Invalid geometry type " + type);
  56193. }
  56194. if (!status.ok() || !geometry.ptr) {
  56195. throw new Error(status.error_msg());
  56196. }
  56197. var numPoints = geometry.num_points();
  56198. if (type === dracoModule.TRIANGULAR_MESH) {
  56199. var numFaces = geometry.num_faces();
  56200. var faceIndices = new dracoModule.DracoInt32Array();
  56201. try {
  56202. var indices = new Uint32Array(numFaces * 3);
  56203. for (var i = 0; i < numFaces; i++) {
  56204. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56205. var offset = i * 3;
  56206. indices[offset + 0] = faceIndices.GetValue(0);
  56207. indices[offset + 1] = faceIndices.GetValue(1);
  56208. indices[offset + 2] = faceIndices.GetValue(2);
  56209. }
  56210. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  56211. }
  56212. finally {
  56213. dracoModule.destroy(faceIndices);
  56214. }
  56215. }
  56216. for (var kind in attributes) {
  56217. var uniqueId = attributes[kind];
  56218. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56219. var dracoData = new dracoModule.DracoFloat32Array();
  56220. try {
  56221. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56222. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56223. for (var i = 0; i < babylonData.length; i++) {
  56224. babylonData[i] = dracoData.GetValue(i);
  56225. }
  56226. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  56227. }
  56228. finally {
  56229. dracoModule.destroy(dracoData);
  56230. }
  56231. }
  56232. }
  56233. finally {
  56234. if (geometry) {
  56235. dracoModule.destroy(geometry);
  56236. }
  56237. dracoModule.destroy(decoder);
  56238. dracoModule.destroy(buffer);
  56239. }
  56240. _self.postMessage("done");
  56241. };
  56242. _self.onmessage = function (event) {
  56243. switch (event.data.id) {
  56244. case "initDecoder": {
  56245. importScripts(event.data.url);
  56246. break;
  56247. }
  56248. case "decodeMesh": {
  56249. decodeMesh(event.data.data, event.data.attributes);
  56250. break;
  56251. }
  56252. }
  56253. };
  56254. };
  56255. DracoCompression._GetDefaultDecoderUrl = function () {
  56256. if (!BABYLON.Tools.IsWindowObjectExist) {
  56257. return null;
  56258. }
  56259. for (var i = 0; i < document.scripts.length; i++) {
  56260. if (document.scripts[i].type === "text/x-draco-decoder") {
  56261. return document.scripts[i].src;
  56262. }
  56263. }
  56264. return null;
  56265. };
  56266. /**
  56267. * Gets the url to the draco decoder if available.
  56268. */
  56269. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  56270. return DracoCompression;
  56271. }());
  56272. BABYLON.DracoCompression = DracoCompression;
  56273. })(BABYLON || (BABYLON = {}));
  56274. //# sourceMappingURL=babylon.dracoCompression.js.map
  56275. var BABYLON;
  56276. (function (BABYLON) {
  56277. var AudioEngine = /** @class */ (function () {
  56278. function AudioEngine() {
  56279. this._audioContext = null;
  56280. this._audioContextInitialized = false;
  56281. this.canUseWebAudio = false;
  56282. this.WarnedWebAudioUnsupported = false;
  56283. this.unlocked = false;
  56284. this.isMP3supported = false;
  56285. this.isOGGsupported = false;
  56286. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56287. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56288. this.canUseWebAudio = true;
  56289. }
  56290. var audioElem = document.createElement('audio');
  56291. try {
  56292. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56293. this.isMP3supported = true;
  56294. }
  56295. }
  56296. catch (e) {
  56297. // protect error during capability check.
  56298. }
  56299. try {
  56300. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56301. this.isOGGsupported = true;
  56302. }
  56303. }
  56304. catch (e) {
  56305. // protect error during capability check.
  56306. }
  56307. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56308. this._unlockiOSaudio();
  56309. }
  56310. else {
  56311. this.unlocked = true;
  56312. }
  56313. }
  56314. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56315. get: function () {
  56316. if (!this._audioContextInitialized) {
  56317. this._initializeAudioContext();
  56318. }
  56319. return this._audioContext;
  56320. },
  56321. enumerable: true,
  56322. configurable: true
  56323. });
  56324. AudioEngine.prototype._unlockiOSaudio = function () {
  56325. var _this = this;
  56326. var unlockaudio = function () {
  56327. if (!_this.audioContext) {
  56328. return;
  56329. }
  56330. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  56331. var source = _this.audioContext.createBufferSource();
  56332. source.buffer = buffer;
  56333. source.connect(_this.audioContext.destination);
  56334. source.start(0);
  56335. setTimeout(function () {
  56336. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  56337. _this.unlocked = true;
  56338. window.removeEventListener('touchend', unlockaudio, false);
  56339. if (_this.onAudioUnlocked) {
  56340. _this.onAudioUnlocked();
  56341. }
  56342. }
  56343. }, 0);
  56344. };
  56345. window.addEventListener('touchend', unlockaudio, false);
  56346. };
  56347. AudioEngine.prototype._initializeAudioContext = function () {
  56348. try {
  56349. if (this.canUseWebAudio) {
  56350. this._audioContext = new AudioContext();
  56351. // create a global volume gain node
  56352. this.masterGain = this._audioContext.createGain();
  56353. this.masterGain.gain.value = 1;
  56354. this.masterGain.connect(this._audioContext.destination);
  56355. this._audioContextInitialized = true;
  56356. }
  56357. }
  56358. catch (e) {
  56359. this.canUseWebAudio = false;
  56360. BABYLON.Tools.Error("Web Audio: " + e.message);
  56361. }
  56362. };
  56363. AudioEngine.prototype.dispose = function () {
  56364. if (this.canUseWebAudio && this._audioContextInitialized) {
  56365. if (this._connectedAnalyser && this._audioContext) {
  56366. this._connectedAnalyser.stopDebugCanvas();
  56367. this._connectedAnalyser.dispose();
  56368. this.masterGain.disconnect();
  56369. this.masterGain.connect(this._audioContext.destination);
  56370. this._connectedAnalyser = null;
  56371. }
  56372. this.masterGain.gain.value = 1;
  56373. }
  56374. this.WarnedWebAudioUnsupported = false;
  56375. };
  56376. AudioEngine.prototype.getGlobalVolume = function () {
  56377. if (this.canUseWebAudio && this._audioContextInitialized) {
  56378. return this.masterGain.gain.value;
  56379. }
  56380. else {
  56381. return -1;
  56382. }
  56383. };
  56384. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  56385. if (this.canUseWebAudio && this._audioContextInitialized) {
  56386. this.masterGain.gain.value = newVolume;
  56387. }
  56388. };
  56389. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  56390. if (this._connectedAnalyser) {
  56391. this._connectedAnalyser.stopDebugCanvas();
  56392. }
  56393. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  56394. this._connectedAnalyser = analyser;
  56395. this.masterGain.disconnect();
  56396. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  56397. }
  56398. };
  56399. return AudioEngine;
  56400. }());
  56401. BABYLON.AudioEngine = AudioEngine;
  56402. })(BABYLON || (BABYLON = {}));
  56403. //# sourceMappingURL=babylon.audioEngine.js.map
  56404. var BABYLON;
  56405. (function (BABYLON) {
  56406. var Sound = /** @class */ (function () {
  56407. /**
  56408. * Create a sound and attach it to a scene
  56409. * @param name Name of your sound
  56410. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  56411. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  56412. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  56413. */
  56414. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  56415. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  56416. var _this = this;
  56417. this.autoplay = false;
  56418. this.loop = false;
  56419. this.useCustomAttenuation = false;
  56420. this.spatialSound = false;
  56421. this.refDistance = 1;
  56422. this.rolloffFactor = 1;
  56423. this.maxDistance = 100;
  56424. this.distanceModel = "linear";
  56425. this._panningModel = "equalpower";
  56426. this._playbackRate = 1;
  56427. this._streaming = false;
  56428. this._startTime = 0;
  56429. this._startOffset = 0;
  56430. this._position = BABYLON.Vector3.Zero();
  56431. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  56432. this._volume = 1;
  56433. this._isReadyToPlay = false;
  56434. this.isPlaying = false;
  56435. this.isPaused = false;
  56436. this._isDirectional = false;
  56437. // Used if you'd like to create a directional sound.
  56438. // If not set, the sound will be omnidirectional
  56439. this._coneInnerAngle = 360;
  56440. this._coneOuterAngle = 360;
  56441. this._coneOuterGain = 0;
  56442. this._isOutputConnected = false;
  56443. this._urlType = "Unknown";
  56444. this.name = name;
  56445. this._scene = scene;
  56446. this._readyToPlayCallback = readyToPlayCallback;
  56447. // Default custom attenuation function is a linear attenuation
  56448. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  56449. if (currentDistance < maxDistance) {
  56450. return currentVolume * (1 - currentDistance / maxDistance);
  56451. }
  56452. else {
  56453. return 0;
  56454. }
  56455. };
  56456. if (options) {
  56457. this.autoplay = options.autoplay || false;
  56458. this.loop = options.loop || false;
  56459. // if volume === 0, we need another way to check this option
  56460. if (options.volume !== undefined) {
  56461. this._volume = options.volume;
  56462. }
  56463. this.spatialSound = options.spatialSound || false;
  56464. this.maxDistance = options.maxDistance || 100;
  56465. this.useCustomAttenuation = options.useCustomAttenuation || false;
  56466. this.rolloffFactor = options.rolloffFactor || 1;
  56467. this.refDistance = options.refDistance || 1;
  56468. this.distanceModel = options.distanceModel || "linear";
  56469. this._playbackRate = options.playbackRate || 1;
  56470. this._streaming = options.streaming || false;
  56471. }
  56472. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56473. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  56474. this._soundGain.gain.value = this._volume;
  56475. this._inputAudioNode = this._soundGain;
  56476. this._ouputAudioNode = this._soundGain;
  56477. if (this.spatialSound) {
  56478. this._createSpatialParameters();
  56479. }
  56480. this._scene.mainSoundTrack.AddSound(this);
  56481. var validParameter = true;
  56482. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  56483. if (urlOrArrayBuffer) {
  56484. if (typeof (urlOrArrayBuffer) === "string")
  56485. this._urlType = "String";
  56486. if (Array.isArray(urlOrArrayBuffer))
  56487. this._urlType = "Array";
  56488. if (urlOrArrayBuffer instanceof ArrayBuffer)
  56489. this._urlType = "ArrayBuffer";
  56490. var urls = [];
  56491. var codecSupportedFound = false;
  56492. switch (this._urlType) {
  56493. case "ArrayBuffer":
  56494. if (urlOrArrayBuffer.byteLength > 0) {
  56495. codecSupportedFound = true;
  56496. this._soundLoaded(urlOrArrayBuffer);
  56497. }
  56498. break;
  56499. case "String":
  56500. urls.push(urlOrArrayBuffer);
  56501. case "Array":
  56502. if (urls.length === 0)
  56503. urls = urlOrArrayBuffer;
  56504. // If we found a supported format, we load it immediately and stop the loop
  56505. for (var i = 0; i < urls.length; i++) {
  56506. var url = urls[i];
  56507. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  56508. codecSupportedFound = true;
  56509. }
  56510. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  56511. codecSupportedFound = true;
  56512. }
  56513. if (url.indexOf(".wav", url.length - 4) !== -1) {
  56514. codecSupportedFound = true;
  56515. }
  56516. if (url.indexOf("blob:") !== -1) {
  56517. codecSupportedFound = true;
  56518. }
  56519. if (codecSupportedFound) {
  56520. // Loading sound using XHR2
  56521. if (!this._streaming) {
  56522. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  56523. }
  56524. else {
  56525. this._htmlAudioElement = new Audio(url);
  56526. this._htmlAudioElement.controls = false;
  56527. this._htmlAudioElement.loop = this.loop;
  56528. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  56529. this._htmlAudioElement.preload = "auto";
  56530. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  56531. _this._isReadyToPlay = true;
  56532. if (_this.autoplay) {
  56533. _this.play();
  56534. }
  56535. if (_this._readyToPlayCallback) {
  56536. _this._readyToPlayCallback();
  56537. }
  56538. });
  56539. document.body.appendChild(this._htmlAudioElement);
  56540. }
  56541. break;
  56542. }
  56543. }
  56544. break;
  56545. default:
  56546. validParameter = false;
  56547. break;
  56548. }
  56549. if (!validParameter) {
  56550. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  56551. }
  56552. else {
  56553. if (!codecSupportedFound) {
  56554. this._isReadyToPlay = true;
  56555. // Simulating a ready to play event to avoid breaking code path
  56556. if (this._readyToPlayCallback) {
  56557. window.setTimeout(function () {
  56558. if (_this._readyToPlayCallback) {
  56559. _this._readyToPlayCallback();
  56560. }
  56561. }, 1000);
  56562. }
  56563. }
  56564. }
  56565. }
  56566. }
  56567. else {
  56568. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  56569. this._scene.mainSoundTrack.AddSound(this);
  56570. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  56571. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  56572. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  56573. }
  56574. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  56575. if (this._readyToPlayCallback) {
  56576. window.setTimeout(function () {
  56577. if (_this._readyToPlayCallback) {
  56578. _this._readyToPlayCallback();
  56579. }
  56580. }, 1000);
  56581. }
  56582. }
  56583. }
  56584. Sound.prototype.dispose = function () {
  56585. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  56586. if (this.isPlaying) {
  56587. this.stop();
  56588. }
  56589. this._isReadyToPlay = false;
  56590. if (this.soundTrackId === -1) {
  56591. this._scene.mainSoundTrack.RemoveSound(this);
  56592. }
  56593. else {
  56594. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  56595. }
  56596. if (this._soundGain) {
  56597. this._soundGain.disconnect();
  56598. this._soundGain = null;
  56599. }
  56600. if (this._soundPanner) {
  56601. this._soundPanner.disconnect();
  56602. this._soundPanner = null;
  56603. }
  56604. if (this._soundSource) {
  56605. this._soundSource.disconnect();
  56606. this._soundSource = null;
  56607. }
  56608. this._audioBuffer = null;
  56609. if (this._htmlAudioElement) {
  56610. this._htmlAudioElement.pause();
  56611. this._htmlAudioElement.src = "";
  56612. document.body.removeChild(this._htmlAudioElement);
  56613. }
  56614. if (this._connectedMesh && this._registerFunc) {
  56615. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56616. this._connectedMesh = null;
  56617. }
  56618. }
  56619. };
  56620. Sound.prototype.isReady = function () {
  56621. return this._isReadyToPlay;
  56622. };
  56623. Sound.prototype._soundLoaded = function (audioData) {
  56624. var _this = this;
  56625. if (!BABYLON.Engine.audioEngine.audioContext) {
  56626. return;
  56627. }
  56628. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  56629. _this._audioBuffer = buffer;
  56630. _this._isReadyToPlay = true;
  56631. if (_this.autoplay) {
  56632. _this.play();
  56633. }
  56634. if (_this._readyToPlayCallback) {
  56635. _this._readyToPlayCallback();
  56636. }
  56637. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  56638. };
  56639. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  56640. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56641. this._audioBuffer = audioBuffer;
  56642. this._isReadyToPlay = true;
  56643. }
  56644. };
  56645. Sound.prototype.updateOptions = function (options) {
  56646. if (options) {
  56647. this.loop = options.loop || this.loop;
  56648. this.maxDistance = options.maxDistance || this.maxDistance;
  56649. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  56650. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  56651. this.refDistance = options.refDistance || this.refDistance;
  56652. this.distanceModel = options.distanceModel || this.distanceModel;
  56653. this._playbackRate = options.playbackRate || this._playbackRate;
  56654. this._updateSpatialParameters();
  56655. if (this.isPlaying) {
  56656. if (this._streaming) {
  56657. this._htmlAudioElement.playbackRate = this._playbackRate;
  56658. }
  56659. else {
  56660. if (this._soundSource) {
  56661. this._soundSource.playbackRate.value = this._playbackRate;
  56662. }
  56663. }
  56664. }
  56665. }
  56666. };
  56667. Sound.prototype._createSpatialParameters = function () {
  56668. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56669. if (this._scene.headphone) {
  56670. this._panningModel = "HRTF";
  56671. }
  56672. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  56673. this._updateSpatialParameters();
  56674. this._soundPanner.connect(this._ouputAudioNode);
  56675. this._inputAudioNode = this._soundPanner;
  56676. }
  56677. };
  56678. Sound.prototype._updateSpatialParameters = function () {
  56679. if (this.spatialSound && this._soundPanner) {
  56680. if (this.useCustomAttenuation) {
  56681. // Tricks to disable in a way embedded Web Audio attenuation
  56682. this._soundPanner.distanceModel = "linear";
  56683. this._soundPanner.maxDistance = Number.MAX_VALUE;
  56684. this._soundPanner.refDistance = 1;
  56685. this._soundPanner.rolloffFactor = 1;
  56686. this._soundPanner.panningModel = this._panningModel;
  56687. }
  56688. else {
  56689. this._soundPanner.distanceModel = this.distanceModel;
  56690. this._soundPanner.maxDistance = this.maxDistance;
  56691. this._soundPanner.refDistance = this.refDistance;
  56692. this._soundPanner.rolloffFactor = this.rolloffFactor;
  56693. this._soundPanner.panningModel = this._panningModel;
  56694. }
  56695. }
  56696. };
  56697. Sound.prototype.switchPanningModelToHRTF = function () {
  56698. this._panningModel = "HRTF";
  56699. this._switchPanningModel();
  56700. };
  56701. Sound.prototype.switchPanningModelToEqualPower = function () {
  56702. this._panningModel = "equalpower";
  56703. this._switchPanningModel();
  56704. };
  56705. Sound.prototype._switchPanningModel = function () {
  56706. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56707. this._soundPanner.panningModel = this._panningModel;
  56708. }
  56709. };
  56710. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  56711. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56712. if (this._isOutputConnected) {
  56713. this._ouputAudioNode.disconnect();
  56714. }
  56715. this._ouputAudioNode.connect(soundTrackAudioNode);
  56716. this._isOutputConnected = true;
  56717. }
  56718. };
  56719. /**
  56720. * Transform this sound into a directional source
  56721. * @param coneInnerAngle Size of the inner cone in degree
  56722. * @param coneOuterAngle Size of the outer cone in degree
  56723. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  56724. */
  56725. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  56726. if (coneOuterAngle < coneInnerAngle) {
  56727. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  56728. return;
  56729. }
  56730. this._coneInnerAngle = coneInnerAngle;
  56731. this._coneOuterAngle = coneOuterAngle;
  56732. this._coneOuterGain = coneOuterGain;
  56733. this._isDirectional = true;
  56734. if (this.isPlaying && this.loop) {
  56735. this.stop();
  56736. this.play();
  56737. }
  56738. };
  56739. Sound.prototype.setPosition = function (newPosition) {
  56740. this._position = newPosition;
  56741. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56742. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56743. }
  56744. };
  56745. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  56746. this._localDirection = newLocalDirection;
  56747. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  56748. this._updateDirection();
  56749. }
  56750. };
  56751. Sound.prototype._updateDirection = function () {
  56752. if (!this._connectedMesh || !this._soundPanner) {
  56753. return;
  56754. }
  56755. var mat = this._connectedMesh.getWorldMatrix();
  56756. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  56757. direction.normalize();
  56758. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  56759. };
  56760. Sound.prototype.updateDistanceFromListener = function () {
  56761. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  56762. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  56763. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  56764. }
  56765. };
  56766. Sound.prototype.setAttenuationFunction = function (callback) {
  56767. this._customAttenuationFunction = callback;
  56768. };
  56769. /**
  56770. * Play the sound
  56771. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  56772. * @param offset (optional) Start the sound setting it at a specific time
  56773. */
  56774. Sound.prototype.play = function (time, offset) {
  56775. var _this = this;
  56776. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  56777. try {
  56778. if (this._startOffset < 0) {
  56779. time = -this._startOffset;
  56780. this._startOffset = 0;
  56781. }
  56782. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56783. if (!this._soundSource || !this._streamingSource) {
  56784. if (this.spatialSound && this._soundPanner) {
  56785. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56786. if (this._isDirectional) {
  56787. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  56788. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  56789. this._soundPanner.coneOuterGain = this._coneOuterGain;
  56790. if (this._connectedMesh) {
  56791. this._updateDirection();
  56792. }
  56793. else {
  56794. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  56795. }
  56796. }
  56797. }
  56798. }
  56799. if (this._streaming) {
  56800. if (!this._streamingSource) {
  56801. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  56802. this._htmlAudioElement.onended = function () { _this._onended(); };
  56803. this._htmlAudioElement.playbackRate = this._playbackRate;
  56804. }
  56805. this._streamingSource.disconnect();
  56806. this._streamingSource.connect(this._inputAudioNode);
  56807. this._htmlAudioElement.play();
  56808. }
  56809. else {
  56810. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  56811. this._soundSource.buffer = this._audioBuffer;
  56812. this._soundSource.connect(this._inputAudioNode);
  56813. this._soundSource.loop = this.loop;
  56814. this._soundSource.playbackRate.value = this._playbackRate;
  56815. this._soundSource.onended = function () { _this._onended(); };
  56816. if (this._soundSource.buffer) {
  56817. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  56818. }
  56819. }
  56820. this._startTime = startTime;
  56821. this.isPlaying = true;
  56822. this.isPaused = false;
  56823. }
  56824. catch (ex) {
  56825. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  56826. }
  56827. }
  56828. };
  56829. Sound.prototype._onended = function () {
  56830. this.isPlaying = false;
  56831. if (this.onended) {
  56832. this.onended();
  56833. }
  56834. };
  56835. /**
  56836. * Stop the sound
  56837. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  56838. */
  56839. Sound.prototype.stop = function (time) {
  56840. if (this.isPlaying) {
  56841. if (this._streaming) {
  56842. this._htmlAudioElement.pause();
  56843. // Test needed for Firefox or it will generate an Invalid State Error
  56844. if (this._htmlAudioElement.currentTime > 0) {
  56845. this._htmlAudioElement.currentTime = 0;
  56846. }
  56847. }
  56848. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  56849. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56850. this._soundSource.stop(stopTime);
  56851. this._soundSource.onended = function () { };
  56852. if (!this.isPaused) {
  56853. this._startOffset = 0;
  56854. }
  56855. }
  56856. this.isPlaying = false;
  56857. }
  56858. };
  56859. Sound.prototype.pause = function () {
  56860. if (this.isPlaying) {
  56861. this.isPaused = true;
  56862. if (this._streaming) {
  56863. this._htmlAudioElement.pause();
  56864. }
  56865. else if (BABYLON.Engine.audioEngine.audioContext) {
  56866. this.stop(0);
  56867. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  56868. }
  56869. }
  56870. };
  56871. Sound.prototype.setVolume = function (newVolume, time) {
  56872. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  56873. if (time && BABYLON.Engine.audioEngine.audioContext) {
  56874. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  56875. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  56876. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  56877. }
  56878. else {
  56879. this._soundGain.gain.value = newVolume;
  56880. }
  56881. }
  56882. this._volume = newVolume;
  56883. };
  56884. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  56885. this._playbackRate = newPlaybackRate;
  56886. if (this.isPlaying) {
  56887. if (this._streaming) {
  56888. this._htmlAudioElement.playbackRate = this._playbackRate;
  56889. }
  56890. else if (this._soundSource) {
  56891. this._soundSource.playbackRate.value = this._playbackRate;
  56892. }
  56893. }
  56894. };
  56895. Sound.prototype.getVolume = function () {
  56896. return this._volume;
  56897. };
  56898. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  56899. var _this = this;
  56900. if (this._connectedMesh && this._registerFunc) {
  56901. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56902. this._registerFunc = null;
  56903. }
  56904. this._connectedMesh = meshToConnectTo;
  56905. if (!this.spatialSound) {
  56906. this.spatialSound = true;
  56907. this._createSpatialParameters();
  56908. if (this.isPlaying && this.loop) {
  56909. this.stop();
  56910. this.play();
  56911. }
  56912. }
  56913. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  56914. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  56915. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  56916. };
  56917. Sound.prototype.detachFromMesh = function () {
  56918. if (this._connectedMesh && this._registerFunc) {
  56919. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56920. this._registerFunc = null;
  56921. this._connectedMesh = null;
  56922. }
  56923. };
  56924. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  56925. if (!node.getBoundingInfo) {
  56926. return;
  56927. }
  56928. var mesh = node;
  56929. var boundingInfo = mesh.getBoundingInfo();
  56930. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  56931. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  56932. this._updateDirection();
  56933. }
  56934. };
  56935. Sound.prototype.clone = function () {
  56936. var _this = this;
  56937. if (!this._streaming) {
  56938. var setBufferAndRun = function () {
  56939. if (_this._isReadyToPlay) {
  56940. clonedSound._audioBuffer = _this.getAudioBuffer();
  56941. clonedSound._isReadyToPlay = true;
  56942. if (clonedSound.autoplay) {
  56943. clonedSound.play();
  56944. }
  56945. }
  56946. else {
  56947. window.setTimeout(setBufferAndRun, 300);
  56948. }
  56949. };
  56950. var currentOptions = {
  56951. autoplay: this.autoplay, loop: this.loop,
  56952. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  56953. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  56954. refDistance: this.refDistance, distanceModel: this.distanceModel
  56955. };
  56956. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  56957. if (this.useCustomAttenuation) {
  56958. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  56959. }
  56960. clonedSound.setPosition(this._position);
  56961. clonedSound.setPlaybackRate(this._playbackRate);
  56962. setBufferAndRun();
  56963. return clonedSound;
  56964. }
  56965. else {
  56966. return null;
  56967. }
  56968. };
  56969. Sound.prototype.getAudioBuffer = function () {
  56970. return this._audioBuffer;
  56971. };
  56972. Sound.prototype.serialize = function () {
  56973. var serializationObject = {
  56974. name: this.name,
  56975. url: this.name,
  56976. autoplay: this.autoplay,
  56977. loop: this.loop,
  56978. volume: this._volume,
  56979. spatialSound: this.spatialSound,
  56980. maxDistance: this.maxDistance,
  56981. rolloffFactor: this.rolloffFactor,
  56982. refDistance: this.refDistance,
  56983. distanceModel: this.distanceModel,
  56984. playbackRate: this._playbackRate,
  56985. panningModel: this._panningModel,
  56986. soundTrackId: this.soundTrackId
  56987. };
  56988. if (this.spatialSound) {
  56989. if (this._connectedMesh)
  56990. serializationObject.connectedMeshId = this._connectedMesh.id;
  56991. serializationObject.position = this._position.asArray();
  56992. serializationObject.refDistance = this.refDistance;
  56993. serializationObject.distanceModel = this.distanceModel;
  56994. serializationObject.isDirectional = this._isDirectional;
  56995. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  56996. serializationObject.coneInnerAngle = this._coneInnerAngle;
  56997. serializationObject.coneOuterAngle = this._coneOuterAngle;
  56998. serializationObject.coneOuterGain = this._coneOuterGain;
  56999. }
  57000. return serializationObject;
  57001. };
  57002. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  57003. var soundName = parsedSound.name;
  57004. var soundUrl;
  57005. if (parsedSound.url) {
  57006. soundUrl = rootUrl + parsedSound.url;
  57007. }
  57008. else {
  57009. soundUrl = rootUrl + soundName;
  57010. }
  57011. var options = {
  57012. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  57013. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  57014. rolloffFactor: parsedSound.rolloffFactor,
  57015. refDistance: parsedSound.refDistance,
  57016. distanceModel: parsedSound.distanceModel,
  57017. playbackRate: parsedSound.playbackRate
  57018. };
  57019. var newSound;
  57020. if (!sourceSound) {
  57021. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  57022. scene._addPendingData(newSound);
  57023. }
  57024. else {
  57025. var setBufferAndRun = function () {
  57026. if (sourceSound._isReadyToPlay) {
  57027. newSound._audioBuffer = sourceSound.getAudioBuffer();
  57028. newSound._isReadyToPlay = true;
  57029. if (newSound.autoplay) {
  57030. newSound.play();
  57031. }
  57032. }
  57033. else {
  57034. window.setTimeout(setBufferAndRun, 300);
  57035. }
  57036. };
  57037. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  57038. setBufferAndRun();
  57039. }
  57040. if (parsedSound.position) {
  57041. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  57042. newSound.setPosition(soundPosition);
  57043. }
  57044. if (parsedSound.isDirectional) {
  57045. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  57046. if (parsedSound.localDirectionToMesh) {
  57047. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  57048. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  57049. }
  57050. }
  57051. if (parsedSound.connectedMeshId) {
  57052. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  57053. if (connectedMesh) {
  57054. newSound.attachToMesh(connectedMesh);
  57055. }
  57056. }
  57057. return newSound;
  57058. };
  57059. return Sound;
  57060. }());
  57061. BABYLON.Sound = Sound;
  57062. })(BABYLON || (BABYLON = {}));
  57063. //# sourceMappingURL=babylon.sound.js.map
  57064. var BABYLON;
  57065. (function (BABYLON) {
  57066. var SoundTrack = /** @class */ (function () {
  57067. function SoundTrack(scene, options) {
  57068. this.id = -1;
  57069. this._isMainTrack = false;
  57070. this._isInitialized = false;
  57071. this._scene = scene;
  57072. this.soundCollection = new Array();
  57073. this._options = options;
  57074. if (!this._isMainTrack) {
  57075. this._scene.soundTracks.push(this);
  57076. this.id = this._scene.soundTracks.length - 1;
  57077. }
  57078. }
  57079. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  57080. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57081. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  57082. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  57083. if (this._options) {
  57084. if (this._options.volume) {
  57085. this._outputAudioNode.gain.value = this._options.volume;
  57086. }
  57087. if (this._options.mainTrack) {
  57088. this._isMainTrack = this._options.mainTrack;
  57089. }
  57090. }
  57091. this._isInitialized = true;
  57092. }
  57093. };
  57094. SoundTrack.prototype.dispose = function () {
  57095. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  57096. if (this._connectedAnalyser) {
  57097. this._connectedAnalyser.stopDebugCanvas();
  57098. }
  57099. while (this.soundCollection.length) {
  57100. this.soundCollection[0].dispose();
  57101. }
  57102. if (this._outputAudioNode) {
  57103. this._outputAudioNode.disconnect();
  57104. }
  57105. this._outputAudioNode = null;
  57106. }
  57107. };
  57108. SoundTrack.prototype.AddSound = function (sound) {
  57109. if (!this._isInitialized) {
  57110. this._initializeSoundTrackAudioGraph();
  57111. }
  57112. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57113. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  57114. }
  57115. if (sound.soundTrackId) {
  57116. if (sound.soundTrackId === -1) {
  57117. this._scene.mainSoundTrack.RemoveSound(sound);
  57118. }
  57119. else {
  57120. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  57121. }
  57122. }
  57123. this.soundCollection.push(sound);
  57124. sound.soundTrackId = this.id;
  57125. };
  57126. SoundTrack.prototype.RemoveSound = function (sound) {
  57127. var index = this.soundCollection.indexOf(sound);
  57128. if (index !== -1) {
  57129. this.soundCollection.splice(index, 1);
  57130. }
  57131. };
  57132. SoundTrack.prototype.setVolume = function (newVolume) {
  57133. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57134. this._outputAudioNode.gain.value = newVolume;
  57135. }
  57136. };
  57137. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  57138. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57139. for (var i = 0; i < this.soundCollection.length; i++) {
  57140. this.soundCollection[i].switchPanningModelToHRTF();
  57141. }
  57142. }
  57143. };
  57144. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57145. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57146. for (var i = 0; i < this.soundCollection.length; i++) {
  57147. this.soundCollection[i].switchPanningModelToEqualPower();
  57148. }
  57149. }
  57150. };
  57151. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57152. if (this._connectedAnalyser) {
  57153. this._connectedAnalyser.stopDebugCanvas();
  57154. }
  57155. this._connectedAnalyser = analyser;
  57156. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57157. this._outputAudioNode.disconnect();
  57158. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57159. }
  57160. };
  57161. return SoundTrack;
  57162. }());
  57163. BABYLON.SoundTrack = SoundTrack;
  57164. })(BABYLON || (BABYLON = {}));
  57165. //# sourceMappingURL=babylon.soundtrack.js.map
  57166. var BABYLON;
  57167. (function (BABYLON) {
  57168. var Analyser = /** @class */ (function () {
  57169. function Analyser(scene) {
  57170. this.SMOOTHING = 0.75;
  57171. this.FFT_SIZE = 512;
  57172. this.BARGRAPHAMPLITUDE = 256;
  57173. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57174. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57175. this._scene = scene;
  57176. this._audioEngine = BABYLON.Engine.audioEngine;
  57177. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57178. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57179. this._webAudioAnalyser.minDecibels = -140;
  57180. this._webAudioAnalyser.maxDecibels = 0;
  57181. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57182. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57183. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57184. }
  57185. }
  57186. Analyser.prototype.getFrequencyBinCount = function () {
  57187. if (this._audioEngine.canUseWebAudio) {
  57188. return this._webAudioAnalyser.frequencyBinCount;
  57189. }
  57190. else {
  57191. return 0;
  57192. }
  57193. };
  57194. Analyser.prototype.getByteFrequencyData = function () {
  57195. if (this._audioEngine.canUseWebAudio) {
  57196. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57197. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57198. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57199. }
  57200. return this._byteFreqs;
  57201. };
  57202. Analyser.prototype.getByteTimeDomainData = function () {
  57203. if (this._audioEngine.canUseWebAudio) {
  57204. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57205. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57206. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57207. }
  57208. return this._byteTime;
  57209. };
  57210. Analyser.prototype.getFloatFrequencyData = function () {
  57211. if (this._audioEngine.canUseWebAudio) {
  57212. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57213. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57214. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57215. }
  57216. return this._floatFreqs;
  57217. };
  57218. Analyser.prototype.drawDebugCanvas = function () {
  57219. var _this = this;
  57220. if (this._audioEngine.canUseWebAudio) {
  57221. if (!this._debugCanvas) {
  57222. this._debugCanvas = document.createElement("canvas");
  57223. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57224. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57225. this._debugCanvas.style.position = "absolute";
  57226. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57227. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57228. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57229. document.body.appendChild(this._debugCanvas);
  57230. this._registerFunc = function () {
  57231. _this.drawDebugCanvas();
  57232. };
  57233. this._scene.registerBeforeRender(this._registerFunc);
  57234. }
  57235. if (this._registerFunc && this._debugCanvasContext) {
  57236. var workingArray = this.getByteFrequencyData();
  57237. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57238. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  57239. // Draw the frequency domain chart.
  57240. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  57241. var value = workingArray[i];
  57242. var percent = value / this.BARGRAPHAMPLITUDE;
  57243. var height = this.DEBUGCANVASSIZE.height * percent;
  57244. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  57245. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  57246. var hue = i / this.getFrequencyBinCount() * 360;
  57247. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  57248. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  57249. }
  57250. }
  57251. }
  57252. };
  57253. Analyser.prototype.stopDebugCanvas = function () {
  57254. if (this._debugCanvas) {
  57255. if (this._registerFunc) {
  57256. this._scene.unregisterBeforeRender(this._registerFunc);
  57257. this._registerFunc = null;
  57258. }
  57259. document.body.removeChild(this._debugCanvas);
  57260. this._debugCanvas = null;
  57261. this._debugCanvasContext = null;
  57262. }
  57263. };
  57264. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57265. if (this._audioEngine.canUseWebAudio) {
  57266. inputAudioNode.connect(this._webAudioAnalyser);
  57267. this._webAudioAnalyser.connect(outputAudioNode);
  57268. }
  57269. };
  57270. Analyser.prototype.dispose = function () {
  57271. if (this._audioEngine.canUseWebAudio) {
  57272. this._webAudioAnalyser.disconnect();
  57273. }
  57274. };
  57275. return Analyser;
  57276. }());
  57277. BABYLON.Analyser = Analyser;
  57278. })(BABYLON || (BABYLON = {}));
  57279. //# sourceMappingURL=babylon.analyser.js.map
  57280. var BABYLON;
  57281. (function (BABYLON) {
  57282. var CubeTexture = /** @class */ (function (_super) {
  57283. __extends(CubeTexture, _super);
  57284. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57285. if (extensions === void 0) { extensions = null; }
  57286. if (noMipmap === void 0) { noMipmap = false; }
  57287. if (files === void 0) { files = null; }
  57288. if (onLoad === void 0) { onLoad = null; }
  57289. if (onError === void 0) { onError = null; }
  57290. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57291. if (prefiltered === void 0) { prefiltered = false; }
  57292. if (forcedExtension === void 0) { forcedExtension = null; }
  57293. var _this = _super.call(this, scene) || this;
  57294. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57295. /**
  57296. * Gets or sets the center of the bounding box associated with the cube texture
  57297. * It must define where the camera used to render the texture was set
  57298. */
  57299. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57300. _this.name = rootUrl;
  57301. _this.url = rootUrl;
  57302. _this._noMipmap = noMipmap;
  57303. _this.hasAlpha = false;
  57304. _this._format = format;
  57305. _this._prefiltered = prefiltered;
  57306. _this.isCube = true;
  57307. _this._textureMatrix = BABYLON.Matrix.Identity();
  57308. if (prefiltered) {
  57309. _this.gammaSpace = false;
  57310. }
  57311. if (!rootUrl && !files) {
  57312. return _this;
  57313. }
  57314. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57315. var lastDot = rootUrl.lastIndexOf(".");
  57316. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  57317. var isDDS = (extension === ".dds");
  57318. if (!files) {
  57319. if (!isDDS && !extensions) {
  57320. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  57321. }
  57322. files = [];
  57323. if (extensions) {
  57324. for (var index = 0; index < extensions.length; index++) {
  57325. files.push(rootUrl + extensions[index]);
  57326. }
  57327. }
  57328. }
  57329. _this._files = files;
  57330. if (!_this._texture) {
  57331. if (!scene.useDelayedTextureLoading) {
  57332. if (prefiltered) {
  57333. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  57334. }
  57335. else {
  57336. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  57337. }
  57338. }
  57339. else {
  57340. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57341. }
  57342. }
  57343. else if (onLoad) {
  57344. if (_this._texture.isReady) {
  57345. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  57346. }
  57347. else {
  57348. _this._texture.onLoadedObservable.add(onLoad);
  57349. }
  57350. }
  57351. return _this;
  57352. }
  57353. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  57354. get: function () {
  57355. return this._boundingBoxSize;
  57356. },
  57357. /**
  57358. * Gets or sets the size of the bounding box associated with the cube texture
  57359. * When defined, the cubemap will switch to local mode
  57360. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57361. * @example https://www.babylonjs-playground.com/#RNASML
  57362. */
  57363. set: function (value) {
  57364. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57365. return;
  57366. }
  57367. this._boundingBoxSize = value;
  57368. var scene = this.getScene();
  57369. if (scene) {
  57370. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57371. }
  57372. },
  57373. enumerable: true,
  57374. configurable: true
  57375. });
  57376. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  57377. var rootUrlKey = "";
  57378. files.forEach(function (url) { return rootUrlKey += url; });
  57379. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  57380. };
  57381. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  57382. if (forcedExtension === void 0) { forcedExtension = null; }
  57383. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  57384. };
  57385. // Methods
  57386. CubeTexture.prototype.delayLoad = function () {
  57387. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57388. return;
  57389. }
  57390. var scene = this.getScene();
  57391. if (!scene) {
  57392. return;
  57393. }
  57394. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57395. this._texture = this._getFromCache(this.url, this._noMipmap);
  57396. if (!this._texture) {
  57397. if (this._prefiltered) {
  57398. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  57399. }
  57400. else {
  57401. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  57402. }
  57403. }
  57404. };
  57405. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  57406. return this._textureMatrix;
  57407. };
  57408. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57409. this._textureMatrix = value;
  57410. };
  57411. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57412. var texture = BABYLON.SerializationHelper.Parse(function () {
  57413. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  57414. }, parsedTexture, scene);
  57415. // Local Cubemaps
  57416. if (parsedTexture.boundingBoxPosition) {
  57417. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  57418. }
  57419. if (parsedTexture.boundingBoxSize) {
  57420. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  57421. }
  57422. // Animations
  57423. if (parsedTexture.animations) {
  57424. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  57425. var parsedAnimation = parsedTexture.animations[animationIndex];
  57426. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57427. }
  57428. }
  57429. return texture;
  57430. };
  57431. CubeTexture.prototype.clone = function () {
  57432. var _this = this;
  57433. return BABYLON.SerializationHelper.Clone(function () {
  57434. var scene = _this.getScene();
  57435. if (!scene) {
  57436. return _this;
  57437. }
  57438. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  57439. }, this);
  57440. };
  57441. return CubeTexture;
  57442. }(BABYLON.BaseTexture));
  57443. BABYLON.CubeTexture = CubeTexture;
  57444. })(BABYLON || (BABYLON = {}));
  57445. //# sourceMappingURL=babylon.cubeTexture.js.map
  57446. var BABYLON;
  57447. (function (BABYLON) {
  57448. var RenderTargetTexture = /** @class */ (function (_super) {
  57449. __extends(RenderTargetTexture, _super);
  57450. /**
  57451. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  57452. * or used a shadow, depth texture...
  57453. * @param name The friendly name of the texture
  57454. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  57455. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  57456. * @param generateMipMaps True if mip maps need to be generated after render.
  57457. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  57458. * @param type The type of the buffer in the RTT (int, half float, float...)
  57459. * @param isCube True if a cube texture needs to be created
  57460. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  57461. * @param generateDepthBuffer True to generate a depth buffer
  57462. * @param generateStencilBuffer True to generate a stencil buffer
  57463. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  57464. */
  57465. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  57466. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  57467. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57468. if (isCube === void 0) { isCube = false; }
  57469. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57470. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57471. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  57472. if (isMulti === void 0) { isMulti = false; }
  57473. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57474. _this.isCube = isCube;
  57475. /**
  57476. * Use this list to define the list of mesh you want to render.
  57477. */
  57478. _this.renderList = new Array();
  57479. _this.renderParticles = true;
  57480. _this.renderSprites = false;
  57481. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  57482. _this.ignoreCameraViewport = false;
  57483. // Events
  57484. /**
  57485. * An event triggered when the texture is unbind.
  57486. * @type {BABYLON.Observable}
  57487. */
  57488. _this.onBeforeBindObservable = new BABYLON.Observable();
  57489. /**
  57490. * An event triggered when the texture is unbind.
  57491. * @type {BABYLON.Observable}
  57492. */
  57493. _this.onAfterUnbindObservable = new BABYLON.Observable();
  57494. /**
  57495. * An event triggered before rendering the texture
  57496. * @type {BABYLON.Observable}
  57497. */
  57498. _this.onBeforeRenderObservable = new BABYLON.Observable();
  57499. /**
  57500. * An event triggered after rendering the texture
  57501. * @type {BABYLON.Observable}
  57502. */
  57503. _this.onAfterRenderObservable = new BABYLON.Observable();
  57504. /**
  57505. * An event triggered after the texture clear
  57506. * @type {BABYLON.Observable}
  57507. */
  57508. _this.onClearObservable = new BABYLON.Observable();
  57509. _this._currentRefreshId = -1;
  57510. _this._refreshRate = 1;
  57511. _this._samples = 1;
  57512. /**
  57513. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  57514. * It must define where the camera used to render the texture is set
  57515. */
  57516. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57517. scene = _this.getScene();
  57518. if (!scene) {
  57519. return _this;
  57520. }
  57521. _this._engine = scene.getEngine();
  57522. _this.name = name;
  57523. _this.isRenderTarget = true;
  57524. _this._initialSizeParameter = size;
  57525. _this._processSizeParameter(size);
  57526. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  57527. });
  57528. _this._generateMipMaps = generateMipMaps ? true : false;
  57529. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  57530. // Rendering groups
  57531. _this._renderingManager = new BABYLON.RenderingManager(scene);
  57532. if (isMulti) {
  57533. return _this;
  57534. }
  57535. _this._renderTargetOptions = {
  57536. generateMipMaps: generateMipMaps,
  57537. type: type,
  57538. samplingMode: samplingMode,
  57539. generateDepthBuffer: generateDepthBuffer,
  57540. generateStencilBuffer: generateStencilBuffer
  57541. };
  57542. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  57543. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57544. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57545. }
  57546. if (isCube) {
  57547. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  57548. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  57549. _this._textureMatrix = BABYLON.Matrix.Identity();
  57550. }
  57551. else {
  57552. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  57553. }
  57554. return _this;
  57555. }
  57556. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  57557. get: function () {
  57558. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  57559. },
  57560. enumerable: true,
  57561. configurable: true
  57562. });
  57563. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  57564. get: function () {
  57565. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  57566. },
  57567. enumerable: true,
  57568. configurable: true
  57569. });
  57570. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  57571. get: function () {
  57572. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  57573. },
  57574. enumerable: true,
  57575. configurable: true
  57576. });
  57577. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  57578. set: function (callback) {
  57579. if (this._onAfterUnbindObserver) {
  57580. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  57581. }
  57582. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  57583. },
  57584. enumerable: true,
  57585. configurable: true
  57586. });
  57587. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  57588. set: function (callback) {
  57589. if (this._onBeforeRenderObserver) {
  57590. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57591. }
  57592. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57593. },
  57594. enumerable: true,
  57595. configurable: true
  57596. });
  57597. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  57598. set: function (callback) {
  57599. if (this._onAfterRenderObserver) {
  57600. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57601. }
  57602. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57603. },
  57604. enumerable: true,
  57605. configurable: true
  57606. });
  57607. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  57608. set: function (callback) {
  57609. if (this._onClearObserver) {
  57610. this.onClearObservable.remove(this._onClearObserver);
  57611. }
  57612. this._onClearObserver = this.onClearObservable.add(callback);
  57613. },
  57614. enumerable: true,
  57615. configurable: true
  57616. });
  57617. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  57618. get: function () {
  57619. return this._renderTargetOptions;
  57620. },
  57621. enumerable: true,
  57622. configurable: true
  57623. });
  57624. RenderTargetTexture.prototype._onRatioRescale = function () {
  57625. if (this._sizeRatio) {
  57626. this.resize(this._initialSizeParameter);
  57627. }
  57628. };
  57629. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  57630. get: function () {
  57631. return this._boundingBoxSize;
  57632. },
  57633. /**
  57634. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  57635. * When defined, the cubemap will switch to local mode
  57636. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57637. * @example https://www.babylonjs-playground.com/#RNASML
  57638. */
  57639. set: function (value) {
  57640. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57641. return;
  57642. }
  57643. this._boundingBoxSize = value;
  57644. var scene = this.getScene();
  57645. if (scene) {
  57646. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57647. }
  57648. },
  57649. enumerable: true,
  57650. configurable: true
  57651. });
  57652. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  57653. if (size.ratio) {
  57654. this._sizeRatio = size.ratio;
  57655. this._size = {
  57656. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  57657. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  57658. };
  57659. }
  57660. else {
  57661. this._size = size;
  57662. }
  57663. };
  57664. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  57665. get: function () {
  57666. return this._samples;
  57667. },
  57668. set: function (value) {
  57669. if (this._samples === value) {
  57670. return;
  57671. }
  57672. var scene = this.getScene();
  57673. if (!scene) {
  57674. return;
  57675. }
  57676. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  57677. },
  57678. enumerable: true,
  57679. configurable: true
  57680. });
  57681. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  57682. this._currentRefreshId = -1;
  57683. };
  57684. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  57685. get: function () {
  57686. return this._refreshRate;
  57687. },
  57688. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57689. set: function (value) {
  57690. this._refreshRate = value;
  57691. this.resetRefreshCounter();
  57692. },
  57693. enumerable: true,
  57694. configurable: true
  57695. });
  57696. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  57697. if (!this._postProcessManager) {
  57698. var scene = this.getScene();
  57699. if (!scene) {
  57700. return;
  57701. }
  57702. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  57703. this._postProcesses = new Array();
  57704. }
  57705. this._postProcesses.push(postProcess);
  57706. this._postProcesses[0].autoClear = false;
  57707. };
  57708. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  57709. if (!this._postProcesses) {
  57710. return;
  57711. }
  57712. if (dispose) {
  57713. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  57714. var postProcess = _a[_i];
  57715. postProcess.dispose();
  57716. }
  57717. }
  57718. this._postProcesses = [];
  57719. };
  57720. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  57721. if (!this._postProcesses) {
  57722. return;
  57723. }
  57724. var index = this._postProcesses.indexOf(postProcess);
  57725. if (index === -1) {
  57726. return;
  57727. }
  57728. this._postProcesses.splice(index, 1);
  57729. if (this._postProcesses.length > 0) {
  57730. this._postProcesses[0].autoClear = false;
  57731. }
  57732. };
  57733. RenderTargetTexture.prototype._shouldRender = function () {
  57734. if (this._currentRefreshId === -1) {
  57735. this._currentRefreshId = 1;
  57736. return true;
  57737. }
  57738. if (this.refreshRate === this._currentRefreshId) {
  57739. this._currentRefreshId = 1;
  57740. return true;
  57741. }
  57742. this._currentRefreshId++;
  57743. return false;
  57744. };
  57745. RenderTargetTexture.prototype.getRenderSize = function () {
  57746. if (this._size.width) {
  57747. return this._size.width;
  57748. }
  57749. return this._size;
  57750. };
  57751. RenderTargetTexture.prototype.getRenderWidth = function () {
  57752. if (this._size.width) {
  57753. return this._size.width;
  57754. }
  57755. return this._size;
  57756. };
  57757. RenderTargetTexture.prototype.getRenderHeight = function () {
  57758. if (this._size.width) {
  57759. return this._size.height;
  57760. }
  57761. return this._size;
  57762. };
  57763. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  57764. get: function () {
  57765. return true;
  57766. },
  57767. enumerable: true,
  57768. configurable: true
  57769. });
  57770. RenderTargetTexture.prototype.scale = function (ratio) {
  57771. var newSize = this.getRenderSize() * ratio;
  57772. this.resize(newSize);
  57773. };
  57774. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  57775. if (this.isCube) {
  57776. return this._textureMatrix;
  57777. }
  57778. return _super.prototype.getReflectionTextureMatrix.call(this);
  57779. };
  57780. RenderTargetTexture.prototype.resize = function (size) {
  57781. this.releaseInternalTexture();
  57782. var scene = this.getScene();
  57783. if (!scene) {
  57784. return;
  57785. }
  57786. this._processSizeParameter(size);
  57787. if (this.isCube) {
  57788. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  57789. }
  57790. else {
  57791. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  57792. }
  57793. };
  57794. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  57795. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  57796. if (dumpForDebug === void 0) { dumpForDebug = false; }
  57797. var scene = this.getScene();
  57798. if (!scene) {
  57799. return;
  57800. }
  57801. var engine = scene.getEngine();
  57802. if (this.useCameraPostProcesses !== undefined) {
  57803. useCameraPostProcess = this.useCameraPostProcesses;
  57804. }
  57805. if (this._waitingRenderList) {
  57806. this.renderList = [];
  57807. for (var index = 0; index < this._waitingRenderList.length; index++) {
  57808. var id = this._waitingRenderList[index];
  57809. var mesh_1 = scene.getMeshByID(id);
  57810. if (mesh_1) {
  57811. this.renderList.push(mesh_1);
  57812. }
  57813. }
  57814. delete this._waitingRenderList;
  57815. }
  57816. // Is predicate defined?
  57817. if (this.renderListPredicate) {
  57818. if (this.renderList) {
  57819. this.renderList.splice(0); // Clear previous renderList
  57820. }
  57821. else {
  57822. this.renderList = [];
  57823. }
  57824. var scene = this.getScene();
  57825. if (!scene) {
  57826. return;
  57827. }
  57828. var sceneMeshes = scene.meshes;
  57829. for (var index = 0; index < sceneMeshes.length; index++) {
  57830. var mesh = sceneMeshes[index];
  57831. if (this.renderListPredicate(mesh)) {
  57832. this.renderList.push(mesh);
  57833. }
  57834. }
  57835. }
  57836. this.onBeforeBindObservable.notifyObservers(this);
  57837. // Set custom projection.
  57838. // Needs to be before binding to prevent changing the aspect ratio.
  57839. var camera;
  57840. if (this.activeCamera) {
  57841. camera = this.activeCamera;
  57842. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57843. if (this.activeCamera !== scene.activeCamera) {
  57844. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  57845. }
  57846. }
  57847. else {
  57848. camera = scene.activeCamera;
  57849. if (camera) {
  57850. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57851. }
  57852. }
  57853. // Prepare renderingManager
  57854. this._renderingManager.reset();
  57855. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  57856. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  57857. var sceneRenderId = scene.getRenderId();
  57858. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  57859. var mesh = currentRenderList[meshIndex];
  57860. if (mesh) {
  57861. if (!mesh.isReady(this.refreshRate === 0)) {
  57862. this.resetRefreshCounter();
  57863. continue;
  57864. }
  57865. mesh._preActivateForIntermediateRendering(sceneRenderId);
  57866. var isMasked = void 0;
  57867. if (!this.renderList && camera) {
  57868. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  57869. }
  57870. else {
  57871. isMasked = false;
  57872. }
  57873. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  57874. mesh._activate(sceneRenderId);
  57875. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  57876. var subMesh = mesh.subMeshes[subIndex];
  57877. scene._activeIndices.addCount(subMesh.indexCount, false);
  57878. this._renderingManager.dispatch(subMesh, mesh);
  57879. }
  57880. }
  57881. }
  57882. }
  57883. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  57884. var particleSystem = scene.particleSystems[particleIndex];
  57885. var emitter = particleSystem.emitter;
  57886. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  57887. continue;
  57888. }
  57889. if (currentRenderList.indexOf(emitter) >= 0) {
  57890. this._renderingManager.dispatchParticles(particleSystem);
  57891. }
  57892. }
  57893. if (this.isCube) {
  57894. for (var face = 0; face < 6; face++) {
  57895. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57896. scene.incrementRenderId();
  57897. scene.resetCachedMaterial();
  57898. }
  57899. }
  57900. else {
  57901. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57902. }
  57903. this.onAfterUnbindObservable.notifyObservers(this);
  57904. if (scene.activeCamera) {
  57905. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  57906. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  57907. }
  57908. engine.setViewport(scene.activeCamera.viewport);
  57909. }
  57910. scene.resetCachedMaterial();
  57911. };
  57912. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  57913. var minimum = 128;
  57914. var x = renderDimension * scale;
  57915. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  57916. // Ensure we don't exceed the render dimension (while staying POT)
  57917. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  57918. };
  57919. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57920. var _this = this;
  57921. if (!this._texture) {
  57922. return;
  57923. }
  57924. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  57925. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57926. });
  57927. };
  57928. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  57929. var scene = this.getScene();
  57930. if (!scene) {
  57931. return;
  57932. }
  57933. var engine = scene.getEngine();
  57934. if (!this._texture) {
  57935. return;
  57936. }
  57937. // Bind
  57938. if (this._postProcessManager) {
  57939. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  57940. }
  57941. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  57942. if (this._texture) {
  57943. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  57944. }
  57945. }
  57946. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  57947. // Clear
  57948. if (this.onClearObservable.hasObservers()) {
  57949. this.onClearObservable.notifyObservers(engine);
  57950. }
  57951. else {
  57952. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  57953. }
  57954. if (!this._doNotChangeAspectRatio) {
  57955. scene.updateTransformMatrix(true);
  57956. }
  57957. // Render
  57958. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  57959. if (this._postProcessManager) {
  57960. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  57961. }
  57962. else if (useCameraPostProcess) {
  57963. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  57964. }
  57965. if (!this._doNotChangeAspectRatio) {
  57966. scene.updateTransformMatrix(true);
  57967. }
  57968. // Dump ?
  57969. if (dumpForDebug) {
  57970. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  57971. }
  57972. // Unbind
  57973. if (!this.isCube || faceIndex === 5) {
  57974. if (this.isCube) {
  57975. if (faceIndex === 5) {
  57976. engine.generateMipMapsForCubemap(this._texture);
  57977. }
  57978. }
  57979. this.unbindFrameBuffer(engine, faceIndex);
  57980. }
  57981. else {
  57982. this.onAfterRenderObservable.notifyObservers(faceIndex);
  57983. }
  57984. };
  57985. /**
  57986. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  57987. * This allowed control for front to back rendering or reversly depending of the special needs.
  57988. *
  57989. * @param renderingGroupId The rendering group id corresponding to its index
  57990. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  57991. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  57992. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  57993. */
  57994. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  57995. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  57996. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  57997. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  57998. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  57999. };
  58000. /**
  58001. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  58002. *
  58003. * @param renderingGroupId The rendering group id corresponding to its index
  58004. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  58005. */
  58006. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  58007. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  58008. };
  58009. RenderTargetTexture.prototype.clone = function () {
  58010. var textureSize = this.getSize();
  58011. 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);
  58012. // Base texture
  58013. newTexture.hasAlpha = this.hasAlpha;
  58014. newTexture.level = this.level;
  58015. // RenderTarget Texture
  58016. newTexture.coordinatesMode = this.coordinatesMode;
  58017. if (this.renderList) {
  58018. newTexture.renderList = this.renderList.slice(0);
  58019. }
  58020. return newTexture;
  58021. };
  58022. RenderTargetTexture.prototype.serialize = function () {
  58023. if (!this.name) {
  58024. return null;
  58025. }
  58026. var serializationObject = _super.prototype.serialize.call(this);
  58027. serializationObject.renderTargetSize = this.getRenderSize();
  58028. serializationObject.renderList = [];
  58029. if (this.renderList) {
  58030. for (var index = 0; index < this.renderList.length; index++) {
  58031. serializationObject.renderList.push(this.renderList[index].id);
  58032. }
  58033. }
  58034. return serializationObject;
  58035. };
  58036. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  58037. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  58038. var objBuffer = this.getInternalTexture();
  58039. var scene = this.getScene();
  58040. if (objBuffer && scene) {
  58041. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  58042. }
  58043. };
  58044. RenderTargetTexture.prototype.dispose = function () {
  58045. if (this._postProcessManager) {
  58046. this._postProcessManager.dispose();
  58047. this._postProcessManager = null;
  58048. }
  58049. this.clearPostProcesses(true);
  58050. if (this._resizeObserver) {
  58051. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  58052. this._resizeObserver = null;
  58053. }
  58054. this.renderList = null;
  58055. // Remove from custom render targets
  58056. var scene = this.getScene();
  58057. if (!scene) {
  58058. return;
  58059. }
  58060. var index = scene.customRenderTargets.indexOf(this);
  58061. if (index >= 0) {
  58062. scene.customRenderTargets.splice(index, 1);
  58063. }
  58064. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  58065. var camera = _a[_i];
  58066. index = camera.customRenderTargets.indexOf(this);
  58067. if (index >= 0) {
  58068. camera.customRenderTargets.splice(index, 1);
  58069. }
  58070. }
  58071. _super.prototype.dispose.call(this);
  58072. };
  58073. RenderTargetTexture.prototype._rebuild = function () {
  58074. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58075. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58076. }
  58077. if (this._postProcessManager) {
  58078. this._postProcessManager._rebuild();
  58079. }
  58080. };
  58081. /**
  58082. * Clear the info related to rendering groups preventing retention point in material dispose.
  58083. */
  58084. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  58085. if (this._renderingManager) {
  58086. this._renderingManager.freeRenderingGroups();
  58087. }
  58088. };
  58089. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  58090. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  58091. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  58092. return RenderTargetTexture;
  58093. }(BABYLON.Texture));
  58094. BABYLON.RenderTargetTexture = RenderTargetTexture;
  58095. })(BABYLON || (BABYLON = {}));
  58096. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  58097. var BABYLON;
  58098. (function (BABYLON) {
  58099. ;
  58100. var MultiRenderTarget = /** @class */ (function (_super) {
  58101. __extends(MultiRenderTarget, _super);
  58102. function MultiRenderTarget(name, size, count, scene, options) {
  58103. var _this = this;
  58104. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  58105. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  58106. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  58107. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  58108. _this._engine = scene.getEngine();
  58109. if (!_this.isSupported) {
  58110. _this.dispose();
  58111. return;
  58112. }
  58113. var types = [];
  58114. var samplingModes = [];
  58115. for (var i = 0; i < count; i++) {
  58116. if (options && options.types && options.types[i] !== undefined) {
  58117. types.push(options.types[i]);
  58118. }
  58119. else {
  58120. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58121. }
  58122. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  58123. samplingModes.push(options.samplingModes[i]);
  58124. }
  58125. else {
  58126. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58127. }
  58128. }
  58129. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  58130. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  58131. _this._size = size;
  58132. _this._multiRenderTargetOptions = {
  58133. samplingModes: samplingModes,
  58134. generateMipMaps: generateMipMaps,
  58135. generateDepthBuffer: generateDepthBuffer,
  58136. generateStencilBuffer: generateStencilBuffer,
  58137. generateDepthTexture: generateDepthTexture,
  58138. types: types,
  58139. textureCount: count
  58140. };
  58141. _this._createInternalTextures();
  58142. _this._createTextures();
  58143. return _this;
  58144. }
  58145. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  58146. get: function () {
  58147. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  58148. },
  58149. enumerable: true,
  58150. configurable: true
  58151. });
  58152. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  58153. get: function () {
  58154. return this._textures;
  58155. },
  58156. enumerable: true,
  58157. configurable: true
  58158. });
  58159. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58160. get: function () {
  58161. return this._textures[this._textures.length - 1];
  58162. },
  58163. enumerable: true,
  58164. configurable: true
  58165. });
  58166. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58167. set: function (wrap) {
  58168. if (this._textures) {
  58169. for (var i = 0; i < this._textures.length; i++) {
  58170. this._textures[i].wrapU = wrap;
  58171. }
  58172. }
  58173. },
  58174. enumerable: true,
  58175. configurable: true
  58176. });
  58177. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58178. set: function (wrap) {
  58179. if (this._textures) {
  58180. for (var i = 0; i < this._textures.length; i++) {
  58181. this._textures[i].wrapV = wrap;
  58182. }
  58183. }
  58184. },
  58185. enumerable: true,
  58186. configurable: true
  58187. });
  58188. MultiRenderTarget.prototype._rebuild = function () {
  58189. this.releaseInternalTextures();
  58190. this._createInternalTextures();
  58191. for (var i = 0; i < this._internalTextures.length; i++) {
  58192. var texture = this._textures[i];
  58193. texture._texture = this._internalTextures[i];
  58194. }
  58195. // Keeps references to frame buffer and stencil/depth buffer
  58196. this._texture = this._internalTextures[0];
  58197. };
  58198. MultiRenderTarget.prototype._createInternalTextures = function () {
  58199. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58200. };
  58201. MultiRenderTarget.prototype._createTextures = function () {
  58202. this._textures = [];
  58203. for (var i = 0; i < this._internalTextures.length; i++) {
  58204. var texture = new BABYLON.Texture(null, this.getScene());
  58205. texture._texture = this._internalTextures[i];
  58206. this._textures.push(texture);
  58207. }
  58208. // Keeps references to frame buffer and stencil/depth buffer
  58209. this._texture = this._internalTextures[0];
  58210. };
  58211. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58212. get: function () {
  58213. return this._samples;
  58214. },
  58215. set: function (value) {
  58216. if (this._samples === value) {
  58217. return;
  58218. }
  58219. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58220. },
  58221. enumerable: true,
  58222. configurable: true
  58223. });
  58224. MultiRenderTarget.prototype.resize = function (size) {
  58225. this.releaseInternalTextures();
  58226. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58227. this._createInternalTextures();
  58228. };
  58229. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58230. var _this = this;
  58231. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58232. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58233. });
  58234. };
  58235. MultiRenderTarget.prototype.dispose = function () {
  58236. this.releaseInternalTextures();
  58237. _super.prototype.dispose.call(this);
  58238. };
  58239. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  58240. if (!this._internalTextures) {
  58241. return;
  58242. }
  58243. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  58244. if (this._internalTextures[i] !== undefined) {
  58245. this._internalTextures[i].dispose();
  58246. this._internalTextures.splice(i, 1);
  58247. }
  58248. }
  58249. };
  58250. return MultiRenderTarget;
  58251. }(BABYLON.RenderTargetTexture));
  58252. BABYLON.MultiRenderTarget = MultiRenderTarget;
  58253. })(BABYLON || (BABYLON = {}));
  58254. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  58255. var BABYLON;
  58256. (function (BABYLON) {
  58257. var MirrorTexture = /** @class */ (function (_super) {
  58258. __extends(MirrorTexture, _super);
  58259. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  58260. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58261. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58262. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58263. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58264. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58265. _this._transformMatrix = BABYLON.Matrix.Zero();
  58266. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  58267. _this._adaptiveBlurKernel = 0;
  58268. _this._blurKernelX = 0;
  58269. _this._blurKernelY = 0;
  58270. _this._blurRatio = 1.0;
  58271. _this.ignoreCameraViewport = true;
  58272. _this.onBeforeRenderObservable.add(function () {
  58273. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  58274. _this._savedViewMatrix = scene.getViewMatrix();
  58275. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  58276. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  58277. scene.clipPlane = _this.mirrorPlane;
  58278. scene.getEngine().cullBackFaces = false;
  58279. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  58280. });
  58281. _this.onAfterRenderObservable.add(function () {
  58282. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58283. scene.getEngine().cullBackFaces = true;
  58284. scene._mirroredCameraPosition = null;
  58285. delete scene.clipPlane;
  58286. });
  58287. return _this;
  58288. }
  58289. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58290. get: function () {
  58291. return this._blurRatio;
  58292. },
  58293. set: function (value) {
  58294. if (this._blurRatio === value) {
  58295. return;
  58296. }
  58297. this._blurRatio = value;
  58298. this._preparePostProcesses();
  58299. },
  58300. enumerable: true,
  58301. configurable: true
  58302. });
  58303. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58304. set: function (value) {
  58305. this._adaptiveBlurKernel = value;
  58306. this._autoComputeBlurKernel();
  58307. },
  58308. enumerable: true,
  58309. configurable: true
  58310. });
  58311. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58312. set: function (value) {
  58313. this.blurKernelX = value;
  58314. this.blurKernelY = value;
  58315. },
  58316. enumerable: true,
  58317. configurable: true
  58318. });
  58319. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  58320. get: function () {
  58321. return this._blurKernelX;
  58322. },
  58323. set: function (value) {
  58324. if (this._blurKernelX === value) {
  58325. return;
  58326. }
  58327. this._blurKernelX = value;
  58328. this._preparePostProcesses();
  58329. },
  58330. enumerable: true,
  58331. configurable: true
  58332. });
  58333. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  58334. get: function () {
  58335. return this._blurKernelY;
  58336. },
  58337. set: function (value) {
  58338. if (this._blurKernelY === value) {
  58339. return;
  58340. }
  58341. this._blurKernelY = value;
  58342. this._preparePostProcesses();
  58343. },
  58344. enumerable: true,
  58345. configurable: true
  58346. });
  58347. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  58348. var engine = this.getScene().getEngine();
  58349. var dw = this.getRenderWidth() / engine.getRenderWidth();
  58350. var dh = this.getRenderHeight() / engine.getRenderHeight();
  58351. this.blurKernelX = this._adaptiveBlurKernel * dw;
  58352. this.blurKernelY = this._adaptiveBlurKernel * dh;
  58353. };
  58354. MirrorTexture.prototype._onRatioRescale = function () {
  58355. if (this._sizeRatio) {
  58356. this.resize(this._initialSizeParameter);
  58357. if (!this._adaptiveBlurKernel) {
  58358. this._preparePostProcesses();
  58359. }
  58360. }
  58361. if (this._adaptiveBlurKernel) {
  58362. this._autoComputeBlurKernel();
  58363. }
  58364. };
  58365. MirrorTexture.prototype._preparePostProcesses = function () {
  58366. this.clearPostProcesses(true);
  58367. if (this._blurKernelX && this._blurKernelY) {
  58368. var engine = this.getScene().getEngine();
  58369. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58370. 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);
  58371. this._blurX.autoClear = false;
  58372. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  58373. this._blurX.inputTexture = this._texture;
  58374. }
  58375. else {
  58376. this._blurX.alwaysForcePOT = true;
  58377. }
  58378. 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);
  58379. this._blurY.autoClear = false;
  58380. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  58381. this.addPostProcess(this._blurX);
  58382. this.addPostProcess(this._blurY);
  58383. }
  58384. else {
  58385. if (this._blurY) {
  58386. this.removePostProcess(this._blurY);
  58387. this._blurY.dispose();
  58388. this._blurY = null;
  58389. }
  58390. if (this._blurX) {
  58391. this.removePostProcess(this._blurX);
  58392. this._blurX.dispose();
  58393. this._blurX = null;
  58394. }
  58395. }
  58396. };
  58397. MirrorTexture.prototype.clone = function () {
  58398. var scene = this.getScene();
  58399. if (!scene) {
  58400. return this;
  58401. }
  58402. var textureSize = this.getSize();
  58403. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  58404. // Base texture
  58405. newTexture.hasAlpha = this.hasAlpha;
  58406. newTexture.level = this.level;
  58407. // Mirror Texture
  58408. newTexture.mirrorPlane = this.mirrorPlane.clone();
  58409. if (this.renderList) {
  58410. newTexture.renderList = this.renderList.slice(0);
  58411. }
  58412. return newTexture;
  58413. };
  58414. MirrorTexture.prototype.serialize = function () {
  58415. if (!this.name) {
  58416. return null;
  58417. }
  58418. var serializationObject = _super.prototype.serialize.call(this);
  58419. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  58420. return serializationObject;
  58421. };
  58422. return MirrorTexture;
  58423. }(BABYLON.RenderTargetTexture));
  58424. BABYLON.MirrorTexture = MirrorTexture;
  58425. })(BABYLON || (BABYLON = {}));
  58426. //# sourceMappingURL=babylon.mirrorTexture.js.map
  58427. var BABYLON;
  58428. (function (BABYLON) {
  58429. /**
  58430. * Creates a refraction texture used by refraction channel of the standard material.
  58431. * @param name the texture name
  58432. * @param size size of the underlying texture
  58433. * @param scene root scene
  58434. */
  58435. var RefractionTexture = /** @class */ (function (_super) {
  58436. __extends(RefractionTexture, _super);
  58437. function RefractionTexture(name, size, scene, generateMipMaps) {
  58438. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  58439. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  58440. _this.depth = 2.0;
  58441. _this.onBeforeRenderObservable.add(function () {
  58442. scene.clipPlane = _this.refractionPlane;
  58443. });
  58444. _this.onAfterRenderObservable.add(function () {
  58445. delete scene.clipPlane;
  58446. });
  58447. return _this;
  58448. }
  58449. RefractionTexture.prototype.clone = function () {
  58450. var scene = this.getScene();
  58451. if (!scene) {
  58452. return this;
  58453. }
  58454. var textureSize = this.getSize();
  58455. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  58456. // Base texture
  58457. newTexture.hasAlpha = this.hasAlpha;
  58458. newTexture.level = this.level;
  58459. // Refraction Texture
  58460. newTexture.refractionPlane = this.refractionPlane.clone();
  58461. if (this.renderList) {
  58462. newTexture.renderList = this.renderList.slice(0);
  58463. }
  58464. newTexture.depth = this.depth;
  58465. return newTexture;
  58466. };
  58467. RefractionTexture.prototype.serialize = function () {
  58468. if (!this.name) {
  58469. return null;
  58470. }
  58471. var serializationObject = _super.prototype.serialize.call(this);
  58472. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  58473. serializationObject.depth = this.depth;
  58474. return serializationObject;
  58475. };
  58476. return RefractionTexture;
  58477. }(BABYLON.RenderTargetTexture));
  58478. BABYLON.RefractionTexture = RefractionTexture;
  58479. })(BABYLON || (BABYLON = {}));
  58480. //# sourceMappingURL=babylon.refractionTexture.js.map
  58481. var BABYLON;
  58482. (function (BABYLON) {
  58483. var DynamicTexture = /** @class */ (function (_super) {
  58484. __extends(DynamicTexture, _super);
  58485. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  58486. if (scene === void 0) { scene = null; }
  58487. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58488. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58489. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  58490. _this.name = name;
  58491. _this._engine = _this.getScene().getEngine();
  58492. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58493. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58494. _this._generateMipMaps = generateMipMaps;
  58495. if (options.getContext) {
  58496. _this._canvas = options;
  58497. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58498. }
  58499. else {
  58500. _this._canvas = document.createElement("canvas");
  58501. if (options.width) {
  58502. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58503. }
  58504. else {
  58505. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  58506. }
  58507. }
  58508. var textureSize = _this.getSize();
  58509. _this._canvas.width = textureSize.width;
  58510. _this._canvas.height = textureSize.height;
  58511. _this._context = _this._canvas.getContext("2d");
  58512. return _this;
  58513. }
  58514. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  58515. get: function () {
  58516. return true;
  58517. },
  58518. enumerable: true,
  58519. configurable: true
  58520. });
  58521. DynamicTexture.prototype._recreate = function (textureSize) {
  58522. this._canvas.width = textureSize.width;
  58523. this._canvas.height = textureSize.height;
  58524. this.releaseInternalTexture();
  58525. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  58526. };
  58527. DynamicTexture.prototype.scale = function (ratio) {
  58528. var textureSize = this.getSize();
  58529. textureSize.width *= ratio;
  58530. textureSize.height *= ratio;
  58531. this._recreate(textureSize);
  58532. };
  58533. DynamicTexture.prototype.scaleTo = function (width, height) {
  58534. var textureSize = this.getSize();
  58535. textureSize.width = width;
  58536. textureSize.height = height;
  58537. this._recreate(textureSize);
  58538. };
  58539. DynamicTexture.prototype.getContext = function () {
  58540. return this._context;
  58541. };
  58542. DynamicTexture.prototype.clear = function () {
  58543. var size = this.getSize();
  58544. this._context.fillRect(0, 0, size.width, size.height);
  58545. };
  58546. DynamicTexture.prototype.update = function (invertY) {
  58547. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  58548. };
  58549. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  58550. if (update === void 0) { update = true; }
  58551. var size = this.getSize();
  58552. if (clearColor) {
  58553. this._context.fillStyle = clearColor;
  58554. this._context.fillRect(0, 0, size.width, size.height);
  58555. }
  58556. this._context.font = font;
  58557. if (x === null || x === undefined) {
  58558. var textSize = this._context.measureText(text);
  58559. x = (size.width - textSize.width) / 2;
  58560. }
  58561. if (y === null || y === undefined) {
  58562. var fontSize = parseInt((font.replace(/\D/g, '')));
  58563. ;
  58564. y = (size.height / 2) + (fontSize / 3.65);
  58565. }
  58566. this._context.fillStyle = color;
  58567. this._context.fillText(text, x, y);
  58568. if (update) {
  58569. this.update(invertY);
  58570. }
  58571. };
  58572. DynamicTexture.prototype.clone = function () {
  58573. var scene = this.getScene();
  58574. if (!scene) {
  58575. return this;
  58576. }
  58577. var textureSize = this.getSize();
  58578. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  58579. // Base texture
  58580. newTexture.hasAlpha = this.hasAlpha;
  58581. newTexture.level = this.level;
  58582. // Dynamic Texture
  58583. newTexture.wrapU = this.wrapU;
  58584. newTexture.wrapV = this.wrapV;
  58585. return newTexture;
  58586. };
  58587. DynamicTexture.prototype._rebuild = function () {
  58588. this.update();
  58589. };
  58590. return DynamicTexture;
  58591. }(BABYLON.Texture));
  58592. BABYLON.DynamicTexture = DynamicTexture;
  58593. })(BABYLON || (BABYLON = {}));
  58594. //# sourceMappingURL=babylon.dynamicTexture.js.map
  58595. var BABYLON;
  58596. (function (BABYLON) {
  58597. var VideoTexture = /** @class */ (function (_super) {
  58598. __extends(VideoTexture, _super);
  58599. /**
  58600. * Creates a video texture.
  58601. * Sample : https://doc.babylonjs.com/how_to/video_texture
  58602. * @param {string | null} name optional name, will detect from video source, if not defined
  58603. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  58604. * @param {BABYLON.Scene} scene is obviously the current scene.
  58605. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  58606. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  58607. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  58608. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  58609. */
  58610. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  58611. if (generateMipMaps === void 0) { generateMipMaps = false; }
  58612. if (invertY === void 0) { invertY = false; }
  58613. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58614. if (settings === void 0) { settings = {
  58615. autoPlay: true,
  58616. loop: true,
  58617. autoUpdateTexture: true,
  58618. }; }
  58619. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58620. _this._createInternalTexture = function () {
  58621. if (_this._texture != null) {
  58622. return;
  58623. }
  58624. if (!_this._engine.needPOTTextures ||
  58625. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  58626. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58627. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58628. }
  58629. else {
  58630. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58631. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58632. _this._generateMipMaps = false;
  58633. }
  58634. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  58635. _this._texture.isReady = true;
  58636. _this._updateInternalTexture();
  58637. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  58638. _this.onLoadObservable.notifyObservers(_this);
  58639. }
  58640. };
  58641. _this.reset = function () {
  58642. if (_this._texture == null) {
  58643. return;
  58644. }
  58645. _this._texture.dispose();
  58646. _this._texture = null;
  58647. };
  58648. _this._updateInternalTexture = function (e) {
  58649. if (_this._texture == null || !_this._texture.isReady) {
  58650. return;
  58651. }
  58652. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  58653. return;
  58654. }
  58655. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  58656. };
  58657. _this._engine = _this.getScene().getEngine();
  58658. _this._generateMipMaps = generateMipMaps;
  58659. _this._samplingMode = samplingMode;
  58660. _this.autoUpdateTexture = settings.autoUpdateTexture;
  58661. _this.name = name || _this._getName(src);
  58662. _this.video = _this._getVideo(src);
  58663. if (settings.autoPlay !== undefined) {
  58664. _this.video.autoplay = settings.autoPlay;
  58665. }
  58666. if (settings.loop !== undefined) {
  58667. _this.video.loop = settings.loop;
  58668. }
  58669. _this.video.addEventListener("canplay", _this._createInternalTexture);
  58670. _this.video.addEventListener("paused", _this._updateInternalTexture);
  58671. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  58672. _this.video.addEventListener("emptied", _this.reset);
  58673. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  58674. _this._createInternalTexture();
  58675. }
  58676. return _this;
  58677. }
  58678. VideoTexture.prototype._getName = function (src) {
  58679. if (src instanceof HTMLVideoElement) {
  58680. return src.currentSrc;
  58681. }
  58682. if (typeof src === "object") {
  58683. return src.toString();
  58684. }
  58685. return src;
  58686. };
  58687. ;
  58688. VideoTexture.prototype._getVideo = function (src) {
  58689. if (src instanceof HTMLVideoElement) {
  58690. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  58691. return src;
  58692. }
  58693. var video = document.createElement("video");
  58694. if (typeof src === "string") {
  58695. BABYLON.Tools.SetCorsBehavior(src, video);
  58696. video.src = src;
  58697. }
  58698. else {
  58699. BABYLON.Tools.SetCorsBehavior(src[0], video);
  58700. src.forEach(function (url) {
  58701. var source = document.createElement("source");
  58702. source.src = url;
  58703. video.appendChild(source);
  58704. });
  58705. }
  58706. return video;
  58707. };
  58708. ;
  58709. /**
  58710. * Internal method to initiate `update`.
  58711. */
  58712. VideoTexture.prototype._rebuild = function () {
  58713. this.update();
  58714. };
  58715. /**
  58716. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  58717. */
  58718. VideoTexture.prototype.update = function () {
  58719. if (!this.autoUpdateTexture) {
  58720. // Expecting user to call `updateTexture` manually
  58721. return;
  58722. }
  58723. this.updateTexture(true);
  58724. };
  58725. /**
  58726. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  58727. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  58728. */
  58729. VideoTexture.prototype.updateTexture = function (isVisible) {
  58730. if (!isVisible) {
  58731. return;
  58732. }
  58733. if (this.video.paused) {
  58734. return;
  58735. }
  58736. this._updateInternalTexture();
  58737. };
  58738. /**
  58739. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  58740. * @param url New url.
  58741. */
  58742. VideoTexture.prototype.updateURL = function (url) {
  58743. this.video.src = url;
  58744. };
  58745. VideoTexture.prototype.dispose = function () {
  58746. _super.prototype.dispose.call(this);
  58747. this.video.removeEventListener("canplay", this._createInternalTexture);
  58748. this.video.removeEventListener("paused", this._updateInternalTexture);
  58749. this.video.removeEventListener("seeked", this._updateInternalTexture);
  58750. this.video.removeEventListener("emptied", this.reset);
  58751. this.video.pause();
  58752. };
  58753. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  58754. var video = document.createElement("video");
  58755. var constraintsDeviceId;
  58756. if (constraints && constraints.deviceId) {
  58757. constraintsDeviceId = {
  58758. exact: constraints.deviceId,
  58759. };
  58760. }
  58761. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  58762. if (navigator.mediaDevices) {
  58763. navigator.mediaDevices.getUserMedia({ video: constraints })
  58764. .then(function (stream) {
  58765. if (video.mozSrcObject !== undefined) {
  58766. // hack for Firefox < 19
  58767. video.mozSrcObject = stream;
  58768. }
  58769. else {
  58770. video.srcObject = stream;
  58771. }
  58772. var onPlaying = function () {
  58773. if (onReady) {
  58774. onReady(new VideoTexture("video", video, scene, true, true));
  58775. }
  58776. video.removeEventListener("playing", onPlaying);
  58777. };
  58778. video.addEventListener("playing", onPlaying);
  58779. video.play();
  58780. })
  58781. .catch(function (err) {
  58782. BABYLON.Tools.Error(err.name);
  58783. });
  58784. }
  58785. else {
  58786. navigator.getUserMedia =
  58787. navigator.getUserMedia ||
  58788. navigator.webkitGetUserMedia ||
  58789. navigator.mozGetUserMedia ||
  58790. navigator.msGetUserMedia;
  58791. if (navigator.getUserMedia) {
  58792. navigator.getUserMedia({
  58793. video: {
  58794. deviceId: constraintsDeviceId,
  58795. width: {
  58796. min: (constraints && constraints.minWidth) || 256,
  58797. max: (constraints && constraints.maxWidth) || 640,
  58798. },
  58799. height: {
  58800. min: (constraints && constraints.minHeight) || 256,
  58801. max: (constraints && constraints.maxHeight) || 480,
  58802. },
  58803. },
  58804. }, function (stream) {
  58805. if (video.mozSrcObject !== undefined) {
  58806. // hack for Firefox < 19
  58807. video.mozSrcObject = stream;
  58808. }
  58809. else {
  58810. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  58811. }
  58812. video.play();
  58813. if (onReady) {
  58814. onReady(new VideoTexture("video", video, scene, true, true));
  58815. }
  58816. }, function (e) {
  58817. BABYLON.Tools.Error(e.name);
  58818. });
  58819. }
  58820. }
  58821. };
  58822. return VideoTexture;
  58823. }(BABYLON.Texture));
  58824. BABYLON.VideoTexture = VideoTexture;
  58825. })(BABYLON || (BABYLON = {}));
  58826. //# sourceMappingURL=babylon.videoTexture.js.map
  58827. var BABYLON;
  58828. (function (BABYLON) {
  58829. var RawTexture = /** @class */ (function (_super) {
  58830. __extends(RawTexture, _super);
  58831. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  58832. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58833. if (invertY === void 0) { invertY = false; }
  58834. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58835. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58836. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58837. _this.format = format;
  58838. _this._engine = scene.getEngine();
  58839. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  58840. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58841. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58842. return _this;
  58843. }
  58844. RawTexture.prototype.update = function (data) {
  58845. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  58846. };
  58847. // Statics
  58848. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58849. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58850. if (invertY === void 0) { invertY = false; }
  58851. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58852. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  58853. };
  58854. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58855. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58856. if (invertY === void 0) { invertY = false; }
  58857. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58858. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58859. };
  58860. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58861. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58862. if (invertY === void 0) { invertY = false; }
  58863. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58864. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58865. };
  58866. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58867. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58868. if (invertY === void 0) { invertY = false; }
  58869. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58870. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58871. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  58872. };
  58873. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58874. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58875. if (invertY === void 0) { invertY = false; }
  58876. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58877. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58878. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  58879. };
  58880. return RawTexture;
  58881. }(BABYLON.Texture));
  58882. BABYLON.RawTexture = RawTexture;
  58883. })(BABYLON || (BABYLON = {}));
  58884. //# sourceMappingURL=babylon.rawTexture.js.map
  58885. var BABYLON;
  58886. (function (BABYLON) {
  58887. /**
  58888. * PostProcess can be used to apply a shader to a texture after it has been rendered
  58889. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  58890. */
  58891. var PostProcess = /** @class */ (function () {
  58892. /**
  58893. * Creates a new instance of @see PostProcess
  58894. * @param name The name of the PostProcess.
  58895. * @param fragmentUrl The url of the fragment shader to be used.
  58896. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  58897. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  58898. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  58899. * @param camera The camera to apply the render pass to.
  58900. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  58901. * @param engine The engine which the post process will be applied. (default: current engine)
  58902. * @param reusable If the post process can be reused on the same frame. (default: false)
  58903. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  58904. * @param textureType Type of textures used when performing the post process. (default: 0)
  58905. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  58906. * @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
  58907. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  58908. */
  58909. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  58910. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  58911. if (defines === void 0) { defines = null; }
  58912. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58913. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  58914. if (blockCompilation === void 0) { blockCompilation = false; }
  58915. this.name = name;
  58916. /**
  58917. * Width of the texture to apply the post process on
  58918. */
  58919. this.width = -1;
  58920. /**
  58921. * Height of the texture to apply the post process on
  58922. */
  58923. this.height = -1;
  58924. /**
  58925. * If the buffer needs to be cleared before applying the post process. (default: true)
  58926. * Should be set to false if shader will overwrite all previous pixels.
  58927. */
  58928. this.autoClear = true;
  58929. /**
  58930. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  58931. */
  58932. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  58933. /**
  58934. * Animations to be used for the post processing
  58935. */
  58936. this.animations = new Array();
  58937. /**
  58938. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  58939. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  58940. */
  58941. this.enablePixelPerfectMode = false;
  58942. /**
  58943. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  58944. */
  58945. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  58946. /**
  58947. * Force textures to be a power of two (default: false)
  58948. */
  58949. this.alwaysForcePOT = false;
  58950. /**
  58951. * Number of sample textures (default: 1)
  58952. */
  58953. this.samples = 1;
  58954. /**
  58955. * Modify the scale of the post process to be the same as the viewport (default: false)
  58956. */
  58957. this.adaptScaleToCurrentViewport = false;
  58958. this._reusable = false;
  58959. /**
  58960. * Smart array of input and output textures for the post process.
  58961. */
  58962. this._textures = new BABYLON.SmartArray(2);
  58963. /**
  58964. * The index in _textures that corresponds to the output texture.
  58965. */
  58966. this._currentRenderTextureInd = 0;
  58967. this._scaleRatio = new BABYLON.Vector2(1, 1);
  58968. this._texelSize = BABYLON.Vector2.Zero();
  58969. // Events
  58970. /**
  58971. * An event triggered when the postprocess is activated.
  58972. * @type {BABYLON.Observable}
  58973. */
  58974. this.onActivateObservable = new BABYLON.Observable();
  58975. /**
  58976. * An event triggered when the postprocess changes its size.
  58977. * @type {BABYLON.Observable}
  58978. */
  58979. this.onSizeChangedObservable = new BABYLON.Observable();
  58980. /**
  58981. * An event triggered when the postprocess applies its effect.
  58982. * @type {BABYLON.Observable}
  58983. */
  58984. this.onApplyObservable = new BABYLON.Observable();
  58985. /**
  58986. * An event triggered before rendering the postprocess
  58987. * @type {BABYLON.Observable}
  58988. */
  58989. this.onBeforeRenderObservable = new BABYLON.Observable();
  58990. /**
  58991. * An event triggered after rendering the postprocess
  58992. * @type {BABYLON.Observable}
  58993. */
  58994. this.onAfterRenderObservable = new BABYLON.Observable();
  58995. if (camera != null) {
  58996. this._camera = camera;
  58997. this._scene = camera.getScene();
  58998. camera.attachPostProcess(this);
  58999. this._engine = this._scene.getEngine();
  59000. this._scene.postProcesses.push(this);
  59001. }
  59002. else if (engine) {
  59003. this._engine = engine;
  59004. this._engine.postProcesses.push(this);
  59005. }
  59006. this._options = options;
  59007. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  59008. this._reusable = reusable || false;
  59009. this._textureType = textureType;
  59010. this._samplers = samplers || [];
  59011. this._samplers.push("textureSampler");
  59012. this._fragmentUrl = fragmentUrl;
  59013. this._vertexUrl = vertexUrl;
  59014. this._parameters = parameters || [];
  59015. this._parameters.push("scale");
  59016. this._indexParameters = indexParameters;
  59017. if (!blockCompilation) {
  59018. this.updateEffect(defines);
  59019. }
  59020. }
  59021. Object.defineProperty(PostProcess.prototype, "onActivate", {
  59022. /**
  59023. * A function that is added to the onActivateObservable
  59024. */
  59025. set: function (callback) {
  59026. if (this._onActivateObserver) {
  59027. this.onActivateObservable.remove(this._onActivateObserver);
  59028. }
  59029. if (callback) {
  59030. this._onActivateObserver = this.onActivateObservable.add(callback);
  59031. }
  59032. },
  59033. enumerable: true,
  59034. configurable: true
  59035. });
  59036. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  59037. /**
  59038. * A function that is added to the onSizeChangedObservable
  59039. */
  59040. set: function (callback) {
  59041. if (this._onSizeChangedObserver) {
  59042. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  59043. }
  59044. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  59045. },
  59046. enumerable: true,
  59047. configurable: true
  59048. });
  59049. Object.defineProperty(PostProcess.prototype, "onApply", {
  59050. /**
  59051. * A function that is added to the onApplyObservable
  59052. */
  59053. set: function (callback) {
  59054. if (this._onApplyObserver) {
  59055. this.onApplyObservable.remove(this._onApplyObserver);
  59056. }
  59057. this._onApplyObserver = this.onApplyObservable.add(callback);
  59058. },
  59059. enumerable: true,
  59060. configurable: true
  59061. });
  59062. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  59063. /**
  59064. * A function that is added to the onBeforeRenderObservable
  59065. */
  59066. set: function (callback) {
  59067. if (this._onBeforeRenderObserver) {
  59068. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59069. }
  59070. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59071. },
  59072. enumerable: true,
  59073. configurable: true
  59074. });
  59075. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  59076. /**
  59077. * A function that is added to the onAfterRenderObservable
  59078. */
  59079. set: function (callback) {
  59080. if (this._onAfterRenderObserver) {
  59081. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59082. }
  59083. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59084. },
  59085. enumerable: true,
  59086. configurable: true
  59087. });
  59088. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  59089. /**
  59090. * 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
  59091. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  59092. */
  59093. get: function () {
  59094. return this._textures.data[this._currentRenderTextureInd];
  59095. },
  59096. set: function (value) {
  59097. this._forcedOutputTexture = value;
  59098. },
  59099. enumerable: true,
  59100. configurable: true
  59101. });
  59102. /**
  59103. * Gets the camera which post process is applied to.
  59104. * @returns The camera the post process is applied to.
  59105. */
  59106. PostProcess.prototype.getCamera = function () {
  59107. return this._camera;
  59108. };
  59109. Object.defineProperty(PostProcess.prototype, "texelSize", {
  59110. /**
  59111. * Gets the texel size of the postprocess.
  59112. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  59113. */
  59114. get: function () {
  59115. if (this._shareOutputWithPostProcess) {
  59116. return this._shareOutputWithPostProcess.texelSize;
  59117. }
  59118. if (this._forcedOutputTexture) {
  59119. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  59120. }
  59121. return this._texelSize;
  59122. },
  59123. enumerable: true,
  59124. configurable: true
  59125. });
  59126. /**
  59127. * Gets the engine which this post process belongs to.
  59128. * @returns The engine the post process was enabled with.
  59129. */
  59130. PostProcess.prototype.getEngine = function () {
  59131. return this._engine;
  59132. };
  59133. /**
  59134. * The effect that is created when initializing the post process.
  59135. * @returns The created effect corrisponding the the postprocess.
  59136. */
  59137. PostProcess.prototype.getEffect = function () {
  59138. return this._effect;
  59139. };
  59140. /**
  59141. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  59142. * @param postProcess The post process to share the output with.
  59143. * @returns This post process.
  59144. */
  59145. PostProcess.prototype.shareOutputWith = function (postProcess) {
  59146. this._disposeTextures();
  59147. this._shareOutputWithPostProcess = postProcess;
  59148. return this;
  59149. };
  59150. /**
  59151. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  59152. * This should be called if the post process that shares output with this post process is disabled/disposed.
  59153. */
  59154. PostProcess.prototype.useOwnOutput = function () {
  59155. if (this._textures.length == 0) {
  59156. this._textures = new BABYLON.SmartArray(2);
  59157. }
  59158. this._shareOutputWithPostProcess = null;
  59159. };
  59160. /**
  59161. * Updates the effect with the current post process compile time values and recompiles the shader.
  59162. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  59163. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  59164. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  59165. * @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
  59166. * @param onCompiled Called when the shader has been compiled.
  59167. * @param onError Called if there is an error when compiling a shader.
  59168. */
  59169. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  59170. if (defines === void 0) { defines = null; }
  59171. if (uniforms === void 0) { uniforms = null; }
  59172. if (samplers === void 0) { samplers = null; }
  59173. 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);
  59174. };
  59175. /**
  59176. * The post process is reusable if it can be used multiple times within one frame.
  59177. * @returns If the post process is reusable
  59178. */
  59179. PostProcess.prototype.isReusable = function () {
  59180. return this._reusable;
  59181. };
  59182. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  59183. PostProcess.prototype.markTextureDirty = function () {
  59184. this.width = -1;
  59185. };
  59186. /**
  59187. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  59188. * 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.
  59189. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  59190. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  59191. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  59192. */
  59193. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  59194. var _this = this;
  59195. if (sourceTexture === void 0) { sourceTexture = null; }
  59196. camera = camera || this._camera;
  59197. var scene = camera.getScene();
  59198. var engine = scene.getEngine();
  59199. var maxSize = engine.getCaps().maxTextureSize;
  59200. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  59201. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  59202. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  59203. var webVRCamera = camera.parent;
  59204. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  59205. requiredWidth /= 2;
  59206. }
  59207. var desiredWidth = (this._options.width || requiredWidth);
  59208. var desiredHeight = this._options.height || requiredHeight;
  59209. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  59210. if (this.adaptScaleToCurrentViewport) {
  59211. var currentViewport = engine.currentViewport;
  59212. if (currentViewport) {
  59213. desiredWidth *= currentViewport.width;
  59214. desiredHeight *= currentViewport.height;
  59215. }
  59216. }
  59217. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59218. if (!this._options.width) {
  59219. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59220. }
  59221. if (!this._options.height) {
  59222. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59223. }
  59224. }
  59225. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59226. if (this._textures.length > 0) {
  59227. for (var i = 0; i < this._textures.length; i++) {
  59228. this._engine._releaseTexture(this._textures.data[i]);
  59229. }
  59230. this._textures.reset();
  59231. }
  59232. this.width = desiredWidth;
  59233. this.height = desiredHeight;
  59234. var textureSize = { width: this.width, height: this.height };
  59235. var textureOptions = {
  59236. generateMipMaps: false,
  59237. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  59238. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  59239. samplingMode: this.renderTargetSamplingMode,
  59240. type: this._textureType
  59241. };
  59242. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59243. if (this._reusable) {
  59244. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59245. }
  59246. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  59247. this.onSizeChangedObservable.notifyObservers(this);
  59248. }
  59249. this._textures.forEach(function (texture) {
  59250. if (texture.samples !== _this.samples) {
  59251. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  59252. }
  59253. });
  59254. }
  59255. var target;
  59256. if (this._shareOutputWithPostProcess) {
  59257. target = this._shareOutputWithPostProcess.inputTexture;
  59258. }
  59259. else if (this._forcedOutputTexture) {
  59260. target = this._forcedOutputTexture;
  59261. this.width = this._forcedOutputTexture.width;
  59262. this.height = this._forcedOutputTexture.height;
  59263. }
  59264. else {
  59265. target = this.inputTexture;
  59266. }
  59267. // Bind the input of this post process to be used as the output of the previous post process.
  59268. if (this.enablePixelPerfectMode) {
  59269. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  59270. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  59271. }
  59272. else {
  59273. this._scaleRatio.copyFromFloats(1, 1);
  59274. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  59275. }
  59276. this.onActivateObservable.notifyObservers(camera);
  59277. // Clear
  59278. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  59279. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  59280. }
  59281. if (this._reusable) {
  59282. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  59283. }
  59284. };
  59285. Object.defineProperty(PostProcess.prototype, "isSupported", {
  59286. /**
  59287. * If the post process is supported.
  59288. */
  59289. get: function () {
  59290. return this._effect.isSupported;
  59291. },
  59292. enumerable: true,
  59293. configurable: true
  59294. });
  59295. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59296. /**
  59297. * The aspect ratio of the output texture.
  59298. */
  59299. get: function () {
  59300. if (this._shareOutputWithPostProcess) {
  59301. return this._shareOutputWithPostProcess.aspectRatio;
  59302. }
  59303. if (this._forcedOutputTexture) {
  59304. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59305. }
  59306. return this.width / this.height;
  59307. },
  59308. enumerable: true,
  59309. configurable: true
  59310. });
  59311. /**
  59312. * Get a value indicating if the post-process is ready to be used
  59313. * @returns true if the post-process is ready (shader is compiled)
  59314. */
  59315. PostProcess.prototype.isReady = function () {
  59316. return this._effect && this._effect.isReady();
  59317. };
  59318. /**
  59319. * Binds all textures and uniforms to the shader, this will be run on every pass.
  59320. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  59321. */
  59322. PostProcess.prototype.apply = function () {
  59323. // Check
  59324. if (!this._effect || !this._effect.isReady())
  59325. return null;
  59326. // States
  59327. this._engine.enableEffect(this._effect);
  59328. this._engine.setState(false);
  59329. this._engine.setDepthBuffer(false);
  59330. this._engine.setDepthWrite(false);
  59331. // Alpha
  59332. this._engine.setAlphaMode(this.alphaMode);
  59333. if (this.alphaConstants) {
  59334. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  59335. }
  59336. // Bind the output texture of the preivous post process as the input to this post process.
  59337. var source;
  59338. if (this._shareOutputWithPostProcess) {
  59339. source = this._shareOutputWithPostProcess.inputTexture;
  59340. }
  59341. else if (this._forcedOutputTexture) {
  59342. source = this._forcedOutputTexture;
  59343. }
  59344. else {
  59345. source = this.inputTexture;
  59346. }
  59347. this._effect._bindTexture("textureSampler", source);
  59348. // Parameters
  59349. this._effect.setVector2("scale", this._scaleRatio);
  59350. this.onApplyObservable.notifyObservers(this._effect);
  59351. return this._effect;
  59352. };
  59353. PostProcess.prototype._disposeTextures = function () {
  59354. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  59355. return;
  59356. }
  59357. if (this._textures.length > 0) {
  59358. for (var i = 0; i < this._textures.length; i++) {
  59359. this._engine._releaseTexture(this._textures.data[i]);
  59360. }
  59361. }
  59362. this._textures.dispose();
  59363. };
  59364. /**
  59365. * Disposes the post process.
  59366. * @param camera The camera to dispose the post process on.
  59367. */
  59368. PostProcess.prototype.dispose = function (camera) {
  59369. camera = camera || this._camera;
  59370. this._disposeTextures();
  59371. if (this._scene) {
  59372. var index_1 = this._scene.postProcesses.indexOf(this);
  59373. if (index_1 !== -1) {
  59374. this._scene.postProcesses.splice(index_1, 1);
  59375. }
  59376. }
  59377. else {
  59378. var index_2 = this._engine.postProcesses.indexOf(this);
  59379. if (index_2 !== -1) {
  59380. this._engine.postProcesses.splice(index_2, 1);
  59381. }
  59382. }
  59383. if (!camera) {
  59384. return;
  59385. }
  59386. camera.detachPostProcess(this);
  59387. var index = camera._postProcesses.indexOf(this);
  59388. if (index === 0 && camera._postProcesses.length > 0) {
  59389. var firstPostProcess = this._camera._getFirstPostProcess();
  59390. if (firstPostProcess) {
  59391. firstPostProcess.markTextureDirty();
  59392. }
  59393. }
  59394. this.onActivateObservable.clear();
  59395. this.onAfterRenderObservable.clear();
  59396. this.onApplyObservable.clear();
  59397. this.onBeforeRenderObservable.clear();
  59398. this.onSizeChangedObservable.clear();
  59399. };
  59400. return PostProcess;
  59401. }());
  59402. BABYLON.PostProcess = PostProcess;
  59403. })(BABYLON || (BABYLON = {}));
  59404. //# sourceMappingURL=babylon.postProcess.js.map
  59405. var BABYLON;
  59406. (function (BABYLON) {
  59407. var PassPostProcess = /** @class */ (function (_super) {
  59408. __extends(PassPostProcess, _super);
  59409. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  59410. if (camera === void 0) { camera = null; }
  59411. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59412. if (blockCompilation === void 0) { blockCompilation = false; }
  59413. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  59414. }
  59415. return PassPostProcess;
  59416. }(BABYLON.PostProcess));
  59417. BABYLON.PassPostProcess = PassPostProcess;
  59418. })(BABYLON || (BABYLON = {}));
  59419. //# sourceMappingURL=babylon.passPostProcess.js.map
  59420. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59421. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59422. s = arguments[i];
  59423. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59424. t[p] = s[p];
  59425. }
  59426. return t;
  59427. };
  59428. var BABYLON;
  59429. (function (BABYLON) {
  59430. /**
  59431. * Default implementation of @see IShadowGenerator.
  59432. * This is the main object responsible of generating shadows in the framework.
  59433. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  59434. */
  59435. var ShadowGenerator = /** @class */ (function () {
  59436. /**
  59437. * Creates a ShadowGenerator object.
  59438. * A ShadowGenerator is the required tool to use the shadows.
  59439. * Each light casting shadows needs to use its own ShadowGenerator.
  59440. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  59441. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  59442. * @param light The light object generating the shadows.
  59443. * @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.
  59444. */
  59445. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  59446. this._bias = 0.00005;
  59447. this._blurBoxOffset = 1;
  59448. this._blurScale = 2;
  59449. this._blurKernel = 1;
  59450. this._useKernelBlur = false;
  59451. this._filter = ShadowGenerator.FILTER_NONE;
  59452. this._darkness = 0;
  59453. this._transparencyShadow = false;
  59454. /**
  59455. * Controls the extent to which the shadows fade out at the edge of the frustum
  59456. * Used only by directionals and spots
  59457. */
  59458. this.frustumEdgeFalloff = 0;
  59459. /**
  59460. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  59461. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  59462. * It might on the other hand introduce peter panning.
  59463. */
  59464. this.forceBackFacesOnly = false;
  59465. this._lightDirection = BABYLON.Vector3.Zero();
  59466. this._viewMatrix = BABYLON.Matrix.Zero();
  59467. this._projectionMatrix = BABYLON.Matrix.Zero();
  59468. this._transformMatrix = BABYLON.Matrix.Zero();
  59469. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  59470. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  59471. this._currentFaceIndex = 0;
  59472. this._currentFaceIndexCache = 0;
  59473. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  59474. this._mapSize = mapSize;
  59475. this._light = light;
  59476. this._scene = light.getScene();
  59477. light._shadowGenerator = this;
  59478. // Texture type fallback from float to int if not supported.
  59479. var caps = this._scene.getEngine().getCaps();
  59480. if (!useFullFloatFirst) {
  59481. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59482. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59483. }
  59484. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59485. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59486. }
  59487. else {
  59488. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59489. }
  59490. }
  59491. else {
  59492. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59493. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59494. }
  59495. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59496. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59497. }
  59498. else {
  59499. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59500. }
  59501. }
  59502. this._initializeGenerator();
  59503. }
  59504. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  59505. /**
  59506. * Shadow generator mode None: no filtering applied.
  59507. */
  59508. get: function () {
  59509. return ShadowGenerator._FILTER_NONE;
  59510. },
  59511. enumerable: true,
  59512. configurable: true
  59513. });
  59514. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  59515. /**
  59516. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  59517. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  59518. */
  59519. get: function () {
  59520. return ShadowGenerator._FILTER_POISSONSAMPLING;
  59521. },
  59522. enumerable: true,
  59523. configurable: true
  59524. });
  59525. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  59526. /**
  59527. * Shadow generator mode ESM: Exponential Shadow Mapping.
  59528. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59529. */
  59530. get: function () {
  59531. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  59532. },
  59533. enumerable: true,
  59534. configurable: true
  59535. });
  59536. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  59537. /**
  59538. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  59539. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59540. */
  59541. get: function () {
  59542. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  59543. },
  59544. enumerable: true,
  59545. configurable: true
  59546. });
  59547. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  59548. /**
  59549. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  59550. * edge artifacts on steep falloff.
  59551. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59552. */
  59553. get: function () {
  59554. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59555. },
  59556. enumerable: true,
  59557. configurable: true
  59558. });
  59559. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  59560. /**
  59561. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  59562. * edge artifacts on steep falloff.
  59563. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59564. */
  59565. get: function () {
  59566. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59567. },
  59568. enumerable: true,
  59569. configurable: true
  59570. });
  59571. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  59572. /**
  59573. * Gets the bias: offset applied on the depth preventing acnea.
  59574. */
  59575. get: function () {
  59576. return this._bias;
  59577. },
  59578. /**
  59579. * Sets the bias: offset applied on the depth preventing acnea.
  59580. */
  59581. set: function (bias) {
  59582. this._bias = bias;
  59583. },
  59584. enumerable: true,
  59585. configurable: true
  59586. });
  59587. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  59588. /**
  59589. * Gets the blur box offset: offset applied during the blur pass.
  59590. * Only usefull if useKernelBlur = false
  59591. */
  59592. get: function () {
  59593. return this._blurBoxOffset;
  59594. },
  59595. /**
  59596. * Sets the blur box offset: offset applied during the blur pass.
  59597. * Only usefull if useKernelBlur = false
  59598. */
  59599. set: function (value) {
  59600. if (this._blurBoxOffset === value) {
  59601. return;
  59602. }
  59603. this._blurBoxOffset = value;
  59604. this._disposeBlurPostProcesses();
  59605. },
  59606. enumerable: true,
  59607. configurable: true
  59608. });
  59609. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  59610. /**
  59611. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  59612. * 2 means half of the size.
  59613. */
  59614. get: function () {
  59615. return this._blurScale;
  59616. },
  59617. /**
  59618. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  59619. * 2 means half of the size.
  59620. */
  59621. set: function (value) {
  59622. if (this._blurScale === value) {
  59623. return;
  59624. }
  59625. this._blurScale = value;
  59626. this._disposeBlurPostProcesses();
  59627. },
  59628. enumerable: true,
  59629. configurable: true
  59630. });
  59631. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  59632. /**
  59633. * Gets the blur kernel: kernel size of the blur pass.
  59634. * Only usefull if useKernelBlur = true
  59635. */
  59636. get: function () {
  59637. return this._blurKernel;
  59638. },
  59639. /**
  59640. * Sets the blur kernel: kernel size of the blur pass.
  59641. * Only usefull if useKernelBlur = true
  59642. */
  59643. set: function (value) {
  59644. if (this._blurKernel === value) {
  59645. return;
  59646. }
  59647. this._blurKernel = value;
  59648. this._disposeBlurPostProcesses();
  59649. },
  59650. enumerable: true,
  59651. configurable: true
  59652. });
  59653. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  59654. /**
  59655. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  59656. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59657. */
  59658. get: function () {
  59659. return this._useKernelBlur;
  59660. },
  59661. /**
  59662. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  59663. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59664. */
  59665. set: function (value) {
  59666. if (this._useKernelBlur === value) {
  59667. return;
  59668. }
  59669. this._useKernelBlur = value;
  59670. this._disposeBlurPostProcesses();
  59671. },
  59672. enumerable: true,
  59673. configurable: true
  59674. });
  59675. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  59676. /**
  59677. * Gets the depth scale used in ESM mode.
  59678. */
  59679. get: function () {
  59680. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  59681. },
  59682. /**
  59683. * Sets the depth scale used in ESM mode.
  59684. * This can override the scale stored on the light.
  59685. */
  59686. set: function (value) {
  59687. this._depthScale = value;
  59688. },
  59689. enumerable: true,
  59690. configurable: true
  59691. });
  59692. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  59693. /**
  59694. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  59695. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59696. */
  59697. get: function () {
  59698. return this._filter;
  59699. },
  59700. /**
  59701. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  59702. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59703. */
  59704. set: function (value) {
  59705. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  59706. if (this._light.needCube()) {
  59707. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59708. this.useExponentialShadowMap = true;
  59709. return;
  59710. }
  59711. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59712. this.useCloseExponentialShadowMap = true;
  59713. return;
  59714. }
  59715. }
  59716. if (this._filter === value) {
  59717. return;
  59718. }
  59719. this._filter = value;
  59720. this._disposeBlurPostProcesses();
  59721. this._applyFilterValues();
  59722. this._light._markMeshesAsLightDirty();
  59723. },
  59724. enumerable: true,
  59725. configurable: true
  59726. });
  59727. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  59728. /**
  59729. * Gets if the current filter is set to Poisson Sampling aka PCF.
  59730. */
  59731. get: function () {
  59732. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  59733. },
  59734. /**
  59735. * Sets the current filter to Poisson Sampling aka PCF.
  59736. */
  59737. set: function (value) {
  59738. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  59739. return;
  59740. }
  59741. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  59742. },
  59743. enumerable: true,
  59744. configurable: true
  59745. });
  59746. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  59747. /**
  59748. * Gets if the current filter is set to VSM.
  59749. * DEPRECATED. Should use useExponentialShadowMap instead.
  59750. */
  59751. get: function () {
  59752. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59753. return this.useExponentialShadowMap;
  59754. },
  59755. /**
  59756. * Sets the current filter is to VSM.
  59757. * DEPRECATED. Should use useExponentialShadowMap instead.
  59758. */
  59759. set: function (value) {
  59760. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59761. this.useExponentialShadowMap = value;
  59762. },
  59763. enumerable: true,
  59764. configurable: true
  59765. });
  59766. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  59767. /**
  59768. * Gets if the current filter is set to blurred VSM.
  59769. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59770. */
  59771. get: function () {
  59772. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59773. return this.useBlurExponentialShadowMap;
  59774. },
  59775. /**
  59776. * Sets the current filter is to blurred VSM.
  59777. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59778. */
  59779. set: function (value) {
  59780. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59781. this.useBlurExponentialShadowMap = value;
  59782. },
  59783. enumerable: true,
  59784. configurable: true
  59785. });
  59786. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  59787. /**
  59788. * Gets if the current filter is set to ESM.
  59789. */
  59790. get: function () {
  59791. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  59792. },
  59793. /**
  59794. * Sets the current filter is to ESM.
  59795. */
  59796. set: function (value) {
  59797. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  59798. return;
  59799. }
  59800. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59801. },
  59802. enumerable: true,
  59803. configurable: true
  59804. });
  59805. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  59806. /**
  59807. * Gets if the current filter is set to filtered ESM.
  59808. */
  59809. get: function () {
  59810. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  59811. },
  59812. /**
  59813. * Gets if the current filter is set to filtered ESM.
  59814. */
  59815. set: function (value) {
  59816. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59817. return;
  59818. }
  59819. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59820. },
  59821. enumerable: true,
  59822. configurable: true
  59823. });
  59824. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  59825. /**
  59826. * Gets if the current filter is set to "close ESM" (using the inverse of the
  59827. * exponential to prevent steep falloff artifacts).
  59828. */
  59829. get: function () {
  59830. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59831. },
  59832. /**
  59833. * Sets the current filter to "close ESM" (using the inverse of the
  59834. * exponential to prevent steep falloff artifacts).
  59835. */
  59836. set: function (value) {
  59837. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  59838. return;
  59839. }
  59840. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59841. },
  59842. enumerable: true,
  59843. configurable: true
  59844. });
  59845. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  59846. /**
  59847. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  59848. * exponential to prevent steep falloff artifacts).
  59849. */
  59850. get: function () {
  59851. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59852. },
  59853. /**
  59854. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  59855. * exponential to prevent steep falloff artifacts).
  59856. */
  59857. set: function (value) {
  59858. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59859. return;
  59860. }
  59861. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59862. },
  59863. enumerable: true,
  59864. configurable: true
  59865. });
  59866. /**
  59867. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  59868. * 0 means strongest and 1 would means no shadow.
  59869. * @returns the darkness.
  59870. */
  59871. ShadowGenerator.prototype.getDarkness = function () {
  59872. return this._darkness;
  59873. };
  59874. /**
  59875. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  59876. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  59877. * @returns the shadow generator allowing fluent coding.
  59878. */
  59879. ShadowGenerator.prototype.setDarkness = function (darkness) {
  59880. if (darkness >= 1.0)
  59881. this._darkness = 1.0;
  59882. else if (darkness <= 0.0)
  59883. this._darkness = 0.0;
  59884. else
  59885. this._darkness = darkness;
  59886. return this;
  59887. };
  59888. /**
  59889. * Sets the ability to have transparent shadow (boolean).
  59890. * @param transparent True if transparent else False
  59891. * @returns the shadow generator allowing fluent coding
  59892. */
  59893. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  59894. this._transparencyShadow = transparent;
  59895. return this;
  59896. };
  59897. /**
  59898. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  59899. * @returns The render target texture if present otherwise, null
  59900. */
  59901. ShadowGenerator.prototype.getShadowMap = function () {
  59902. return this._shadowMap;
  59903. };
  59904. /**
  59905. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  59906. * @returns The render target texture if the shadow map is present otherwise, null
  59907. */
  59908. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  59909. if (this._shadowMap2) {
  59910. return this._shadowMap2;
  59911. }
  59912. return this._shadowMap;
  59913. };
  59914. /**
  59915. * Helper function to add a mesh and its descendants to the list of shadow casters.
  59916. * @param mesh Mesh to add
  59917. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  59918. * @returns the Shadow Generator itself
  59919. */
  59920. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  59921. if (includeDescendants === void 0) { includeDescendants = true; }
  59922. if (!this._shadowMap) {
  59923. return this;
  59924. }
  59925. if (!this._shadowMap.renderList) {
  59926. this._shadowMap.renderList = [];
  59927. }
  59928. this._shadowMap.renderList.push(mesh);
  59929. if (includeDescendants) {
  59930. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  59931. }
  59932. return this;
  59933. var _a;
  59934. };
  59935. /**
  59936. * Helper function to remove a mesh and its descendants from the list of shadow casters
  59937. * @param mesh Mesh to remove
  59938. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  59939. * @returns the Shadow Generator itself
  59940. */
  59941. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  59942. if (includeDescendants === void 0) { includeDescendants = true; }
  59943. if (!this._shadowMap || !this._shadowMap.renderList) {
  59944. return this;
  59945. }
  59946. var index = this._shadowMap.renderList.indexOf(mesh);
  59947. if (index !== -1) {
  59948. this._shadowMap.renderList.splice(index, 1);
  59949. }
  59950. if (includeDescendants) {
  59951. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  59952. var child = _a[_i];
  59953. this.removeShadowCaster(child);
  59954. }
  59955. }
  59956. return this;
  59957. };
  59958. /**
  59959. * Returns the associated light object.
  59960. * @returns the light generating the shadow
  59961. */
  59962. ShadowGenerator.prototype.getLight = function () {
  59963. return this._light;
  59964. };
  59965. ShadowGenerator.prototype._initializeGenerator = function () {
  59966. this._light._markMeshesAsLightDirty();
  59967. this._initializeShadowMap();
  59968. };
  59969. ShadowGenerator.prototype._initializeShadowMap = function () {
  59970. var _this = this;
  59971. // Render target
  59972. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  59973. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59974. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59975. this._shadowMap.anisotropicFilteringLevel = 1;
  59976. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59977. this._shadowMap.renderParticles = false;
  59978. this._shadowMap.ignoreCameraViewport = true;
  59979. // Record Face Index before render.
  59980. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  59981. _this._currentFaceIndex = faceIndex;
  59982. });
  59983. // Custom render function.
  59984. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  59985. // Blur if required afer render.
  59986. this._shadowMap.onAfterUnbindObservable.add(function () {
  59987. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  59988. return;
  59989. }
  59990. var shadowMap = _this.getShadowMapForRendering();
  59991. if (shadowMap) {
  59992. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  59993. }
  59994. });
  59995. // Clear according to the chosen filter.
  59996. var zero = new BABYLON.Color4(0, 0, 0, 0);
  59997. var one = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59998. this._shadowMap.onClearObservable.add(function (engine) {
  59999. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  60000. engine.clear(zero, true, true, true);
  60001. }
  60002. else {
  60003. engine.clear(one, true, true, true);
  60004. }
  60005. });
  60006. };
  60007. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  60008. var _this = this;
  60009. var engine = this._scene.getEngine();
  60010. var targetSize = this._mapSize / this.blurScale;
  60011. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  60012. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  60013. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60014. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60015. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60016. }
  60017. if (this.useKernelBlur) {
  60018. 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);
  60019. this._kernelBlurXPostprocess.width = targetSize;
  60020. this._kernelBlurXPostprocess.height = targetSize;
  60021. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  60022. effect.setTexture("textureSampler", _this._shadowMap);
  60023. });
  60024. 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);
  60025. this._kernelBlurXPostprocess.autoClear = false;
  60026. this._kernelBlurYPostprocess.autoClear = false;
  60027. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60028. this._kernelBlurXPostprocess.packedFloat = true;
  60029. this._kernelBlurYPostprocess.packedFloat = true;
  60030. }
  60031. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  60032. }
  60033. else {
  60034. 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);
  60035. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  60036. effect.setFloat2("screenSize", targetSize, targetSize);
  60037. effect.setTexture("textureSampler", _this._shadowMap);
  60038. });
  60039. this._boxBlurPostprocess.autoClear = false;
  60040. this._blurPostProcesses = [this._boxBlurPostprocess];
  60041. }
  60042. };
  60043. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60044. var index;
  60045. var engine = this._scene.getEngine();
  60046. if (depthOnlySubMeshes.length) {
  60047. engine.setColorWrite(false);
  60048. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60049. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  60050. }
  60051. engine.setColorWrite(true);
  60052. }
  60053. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60054. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  60055. }
  60056. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60057. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  60058. }
  60059. if (this._transparencyShadow) {
  60060. for (index = 0; index < transparentSubMeshes.length; index++) {
  60061. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  60062. }
  60063. }
  60064. };
  60065. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  60066. var _this = this;
  60067. var mesh = subMesh.getRenderingMesh();
  60068. var scene = this._scene;
  60069. var engine = scene.getEngine();
  60070. var material = subMesh.getMaterial();
  60071. if (!material) {
  60072. return;
  60073. }
  60074. // Culling
  60075. engine.setState(material.backFaceCulling);
  60076. // Managing instances
  60077. var batch = mesh._getInstancesRenderList(subMesh._id);
  60078. if (batch.mustReturn) {
  60079. return;
  60080. }
  60081. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60082. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  60083. engine.enableEffect(this._effect);
  60084. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60085. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  60086. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  60087. this._effect.setVector3("lightPosition", this.getLight().position);
  60088. if (scene.activeCamera) {
  60089. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  60090. }
  60091. // Alpha test
  60092. if (material && material.needAlphaTesting()) {
  60093. var alphaTexture = material.getAlphaTestTexture();
  60094. if (alphaTexture) {
  60095. this._effect.setTexture("diffuseSampler", alphaTexture);
  60096. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  60097. }
  60098. }
  60099. // Bones
  60100. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60101. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  60102. }
  60103. if (this.forceBackFacesOnly) {
  60104. engine.setState(true, 0, false, true);
  60105. }
  60106. // Draw
  60107. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60108. if (this.forceBackFacesOnly) {
  60109. engine.setState(true, 0, false, false);
  60110. }
  60111. }
  60112. else {
  60113. // Need to reset refresh rate of the shadowMap
  60114. if (this._shadowMap) {
  60115. this._shadowMap.resetRefreshCounter();
  60116. }
  60117. }
  60118. };
  60119. ShadowGenerator.prototype._applyFilterValues = function () {
  60120. if (!this._shadowMap) {
  60121. return;
  60122. }
  60123. if (this.filter === ShadowGenerator.FILTER_NONE) {
  60124. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60125. }
  60126. else {
  60127. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60128. }
  60129. };
  60130. /**
  60131. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60132. * @param onCompiled Callback triggered at the and of the effects compilation
  60133. * @param options Sets of optional options forcing the compilation with different modes
  60134. */
  60135. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  60136. var _this = this;
  60137. var localOptions = __assign({ useInstances: false }, options);
  60138. var shadowMap = this.getShadowMap();
  60139. if (!shadowMap) {
  60140. if (onCompiled) {
  60141. onCompiled(this);
  60142. }
  60143. return;
  60144. }
  60145. var renderList = shadowMap.renderList;
  60146. if (!renderList) {
  60147. if (onCompiled) {
  60148. onCompiled(this);
  60149. }
  60150. return;
  60151. }
  60152. var subMeshes = new Array();
  60153. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  60154. var mesh = renderList_1[_i];
  60155. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  60156. }
  60157. if (subMeshes.length === 0) {
  60158. if (onCompiled) {
  60159. onCompiled(this);
  60160. }
  60161. return;
  60162. }
  60163. var currentIndex = 0;
  60164. var checkReady = function () {
  60165. if (!_this._scene || !_this._scene.getEngine()) {
  60166. return;
  60167. }
  60168. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  60169. currentIndex++;
  60170. if (currentIndex >= subMeshes.length) {
  60171. if (onCompiled) {
  60172. onCompiled(_this);
  60173. }
  60174. return;
  60175. }
  60176. }
  60177. setTimeout(checkReady, 16);
  60178. };
  60179. checkReady();
  60180. };
  60181. /**
  60182. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60183. * @param options Sets of optional options forcing the compilation with different modes
  60184. * @returns A promise that resolves when the compilation completes
  60185. */
  60186. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  60187. var _this = this;
  60188. return new Promise(function (resolve) {
  60189. _this.forceCompilation(function () {
  60190. resolve();
  60191. }, options);
  60192. });
  60193. };
  60194. /**
  60195. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  60196. * @param subMesh The submesh we want to render in the shadow map
  60197. * @param useInstances Defines wether will draw in the map using instances
  60198. * @returns true if ready otherwise, false
  60199. */
  60200. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  60201. var defines = [];
  60202. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60203. defines.push("#define FLOAT");
  60204. }
  60205. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60206. defines.push("#define ESM");
  60207. }
  60208. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60209. var mesh = subMesh.getMesh();
  60210. var material = subMesh.getMaterial();
  60211. // Alpha test
  60212. if (material && material.needAlphaTesting()) {
  60213. var alphaTexture = material.getAlphaTestTexture();
  60214. if (alphaTexture) {
  60215. defines.push("#define ALPHATEST");
  60216. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60217. attribs.push(BABYLON.VertexBuffer.UVKind);
  60218. defines.push("#define UV1");
  60219. }
  60220. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60221. if (alphaTexture.coordinatesIndex === 1) {
  60222. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60223. defines.push("#define UV2");
  60224. }
  60225. }
  60226. }
  60227. }
  60228. // Bones
  60229. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60230. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60231. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60232. if (mesh.numBoneInfluencers > 4) {
  60233. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60234. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60235. }
  60236. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60237. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60238. }
  60239. else {
  60240. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60241. }
  60242. // Instances
  60243. if (useInstances) {
  60244. defines.push("#define INSTANCES");
  60245. attribs.push("world0");
  60246. attribs.push("world1");
  60247. attribs.push("world2");
  60248. attribs.push("world3");
  60249. }
  60250. // Get correct effect
  60251. var join = defines.join("\n");
  60252. if (this._cachedDefines !== join) {
  60253. this._cachedDefines = join;
  60254. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  60255. }
  60256. if (!this._effect.isReady()) {
  60257. return false;
  60258. }
  60259. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60260. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  60261. this._initializeBlurRTTAndPostProcesses();
  60262. }
  60263. }
  60264. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  60265. return false;
  60266. }
  60267. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  60268. return false;
  60269. }
  60270. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  60271. return false;
  60272. }
  60273. return true;
  60274. };
  60275. /**
  60276. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  60277. * @param defines Defines of the material we want to update
  60278. * @param lightIndex Index of the light in the enabled light list of the material
  60279. */
  60280. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  60281. var scene = this._scene;
  60282. var light = this._light;
  60283. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60284. return;
  60285. }
  60286. defines["SHADOW" + lightIndex] = true;
  60287. if (this.usePoissonSampling) {
  60288. defines["SHADOWPCF" + lightIndex] = true;
  60289. }
  60290. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60291. defines["SHADOWESM" + lightIndex] = true;
  60292. }
  60293. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60294. defines["SHADOWCLOSEESM" + lightIndex] = true;
  60295. }
  60296. if (light.needCube()) {
  60297. defines["SHADOWCUBE" + lightIndex] = true;
  60298. }
  60299. };
  60300. /**
  60301. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  60302. * defined in the generator but impacting the effect).
  60303. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  60304. * @param effect The effect we are binfing the information for
  60305. */
  60306. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  60307. var light = this._light;
  60308. var scene = this._scene;
  60309. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60310. return;
  60311. }
  60312. var camera = scene.activeCamera;
  60313. if (!camera) {
  60314. return;
  60315. }
  60316. var shadowMap = this.getShadowMap();
  60317. if (!shadowMap) {
  60318. return;
  60319. }
  60320. if (!light.needCube()) {
  60321. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  60322. }
  60323. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  60324. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  60325. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  60326. };
  60327. /**
  60328. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  60329. * (eq to shadow prjection matrix * light transform matrix)
  60330. * @returns The transform matrix used to create the shadow map
  60331. */
  60332. ShadowGenerator.prototype.getTransformMatrix = function () {
  60333. var scene = this._scene;
  60334. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  60335. return this._transformMatrix;
  60336. }
  60337. this._currentRenderID = scene.getRenderId();
  60338. this._currentFaceIndexCache = this._currentFaceIndex;
  60339. var lightPosition = this._light.position;
  60340. if (this._light.computeTransformedInformation()) {
  60341. lightPosition = this._light.transformedPosition;
  60342. }
  60343. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  60344. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  60345. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  60346. }
  60347. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  60348. this._cachedPosition.copyFrom(lightPosition);
  60349. this._cachedDirection.copyFrom(this._lightDirection);
  60350. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  60351. var shadowMap = this.getShadowMap();
  60352. if (shadowMap) {
  60353. var renderList = shadowMap.renderList;
  60354. if (renderList) {
  60355. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  60356. }
  60357. }
  60358. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  60359. }
  60360. return this._transformMatrix;
  60361. };
  60362. /**
  60363. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  60364. * Cube and 2D textures for instance.
  60365. */
  60366. ShadowGenerator.prototype.recreateShadowMap = function () {
  60367. var shadowMap = this._shadowMap;
  60368. if (!shadowMap) {
  60369. return;
  60370. }
  60371. // Track render list.
  60372. var renderList = shadowMap.renderList;
  60373. // Clean up existing data.
  60374. this._disposeRTTandPostProcesses();
  60375. // Reinitializes.
  60376. this._initializeGenerator();
  60377. // Reaffect the filter to ensure a correct fallback if necessary.
  60378. this.filter = this.filter;
  60379. // Reaffect the filter.
  60380. this._applyFilterValues();
  60381. // Reaffect Render List.
  60382. this._shadowMap.renderList = renderList;
  60383. };
  60384. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  60385. if (this._shadowMap2) {
  60386. this._shadowMap2.dispose();
  60387. this._shadowMap2 = null;
  60388. }
  60389. if (this._boxBlurPostprocess) {
  60390. this._boxBlurPostprocess.dispose();
  60391. this._boxBlurPostprocess = null;
  60392. }
  60393. if (this._kernelBlurXPostprocess) {
  60394. this._kernelBlurXPostprocess.dispose();
  60395. this._kernelBlurXPostprocess = null;
  60396. }
  60397. if (this._kernelBlurYPostprocess) {
  60398. this._kernelBlurYPostprocess.dispose();
  60399. this._kernelBlurYPostprocess = null;
  60400. }
  60401. this._blurPostProcesses = [];
  60402. };
  60403. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  60404. if (this._shadowMap) {
  60405. this._shadowMap.dispose();
  60406. this._shadowMap = null;
  60407. }
  60408. this._disposeBlurPostProcesses();
  60409. };
  60410. /**
  60411. * Disposes the ShadowGenerator.
  60412. * Returns nothing.
  60413. */
  60414. ShadowGenerator.prototype.dispose = function () {
  60415. this._disposeRTTandPostProcesses();
  60416. if (this._light) {
  60417. this._light._shadowGenerator = null;
  60418. this._light._markMeshesAsLightDirty();
  60419. }
  60420. };
  60421. /**
  60422. * Serializes the shadow generator setup to a json object.
  60423. * @returns The serialized JSON object
  60424. */
  60425. ShadowGenerator.prototype.serialize = function () {
  60426. var serializationObject = {};
  60427. var shadowMap = this.getShadowMap();
  60428. if (!shadowMap) {
  60429. return serializationObject;
  60430. }
  60431. serializationObject.lightId = this._light.id;
  60432. serializationObject.mapSize = shadowMap.getRenderSize();
  60433. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  60434. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  60435. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60436. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60437. serializationObject.usePoissonSampling = this.usePoissonSampling;
  60438. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  60439. serializationObject.depthScale = this.depthScale;
  60440. serializationObject.darkness = this.getDarkness();
  60441. serializationObject.blurBoxOffset = this.blurBoxOffset;
  60442. serializationObject.blurKernel = this.blurKernel;
  60443. serializationObject.blurScale = this.blurScale;
  60444. serializationObject.useKernelBlur = this.useKernelBlur;
  60445. serializationObject.transparencyShadow = this._transparencyShadow;
  60446. serializationObject.renderList = [];
  60447. if (shadowMap.renderList) {
  60448. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  60449. var mesh = shadowMap.renderList[meshIndex];
  60450. serializationObject.renderList.push(mesh.id);
  60451. }
  60452. }
  60453. return serializationObject;
  60454. };
  60455. /**
  60456. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  60457. * @param parsedShadowGenerator The JSON object to parse
  60458. * @param scene The scene to create the shadow map for
  60459. * @returns The parsed shadow generator
  60460. */
  60461. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  60462. //casting to point light, as light is missing the position attr and typescript complains.
  60463. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  60464. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  60465. var shadowMap = shadowGenerator.getShadowMap();
  60466. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  60467. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  60468. meshes.forEach(function (mesh) {
  60469. if (!shadowMap) {
  60470. return;
  60471. }
  60472. if (!shadowMap.renderList) {
  60473. shadowMap.renderList = [];
  60474. }
  60475. shadowMap.renderList.push(mesh);
  60476. });
  60477. }
  60478. if (parsedShadowGenerator.usePoissonSampling) {
  60479. shadowGenerator.usePoissonSampling = true;
  60480. }
  60481. else if (parsedShadowGenerator.useExponentialShadowMap) {
  60482. shadowGenerator.useExponentialShadowMap = true;
  60483. }
  60484. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  60485. shadowGenerator.useBlurExponentialShadowMap = true;
  60486. }
  60487. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  60488. shadowGenerator.useCloseExponentialShadowMap = true;
  60489. }
  60490. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  60491. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  60492. }
  60493. else if (parsedShadowGenerator.useVarianceShadowMap) {
  60494. shadowGenerator.useExponentialShadowMap = true;
  60495. }
  60496. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  60497. shadowGenerator.useBlurExponentialShadowMap = true;
  60498. }
  60499. if (parsedShadowGenerator.depthScale) {
  60500. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  60501. }
  60502. if (parsedShadowGenerator.blurScale) {
  60503. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  60504. }
  60505. if (parsedShadowGenerator.blurBoxOffset) {
  60506. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  60507. }
  60508. if (parsedShadowGenerator.useKernelBlur) {
  60509. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  60510. }
  60511. if (parsedShadowGenerator.blurKernel) {
  60512. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  60513. }
  60514. if (parsedShadowGenerator.bias !== undefined) {
  60515. shadowGenerator.bias = parsedShadowGenerator.bias;
  60516. }
  60517. if (parsedShadowGenerator.darkness) {
  60518. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  60519. }
  60520. if (parsedShadowGenerator.transparencyShadow) {
  60521. shadowGenerator.setTransparencyShadow(true);
  60522. }
  60523. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  60524. return shadowGenerator;
  60525. };
  60526. ShadowGenerator._FILTER_NONE = 0;
  60527. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  60528. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  60529. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  60530. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  60531. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  60532. return ShadowGenerator;
  60533. }());
  60534. BABYLON.ShadowGenerator = ShadowGenerator;
  60535. })(BABYLON || (BABYLON = {}));
  60536. //# sourceMappingURL=babylon.shadowGenerator.js.map
  60537. var BABYLON;
  60538. (function (BABYLON) {
  60539. var DefaultLoadingScreen = /** @class */ (function () {
  60540. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  60541. if (_loadingText === void 0) { _loadingText = ""; }
  60542. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  60543. var _this = this;
  60544. this._renderingCanvas = _renderingCanvas;
  60545. this._loadingText = _loadingText;
  60546. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  60547. // Resize
  60548. this._resizeLoadingUI = function () {
  60549. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  60550. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  60551. if (!_this._loadingDiv) {
  60552. return;
  60553. }
  60554. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  60555. _this._loadingDiv.style.left = canvasRect.left + "px";
  60556. _this._loadingDiv.style.top = canvasRect.top + "px";
  60557. _this._loadingDiv.style.width = canvasRect.width + "px";
  60558. _this._loadingDiv.style.height = canvasRect.height + "px";
  60559. };
  60560. }
  60561. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  60562. if (this._loadingDiv) {
  60563. // Do not add a loading screen if there is already one
  60564. return;
  60565. }
  60566. this._loadingDiv = document.createElement("div");
  60567. this._loadingDiv.id = "babylonjsLoadingDiv";
  60568. this._loadingDiv.style.opacity = "0";
  60569. this._loadingDiv.style.transition = "opacity 1.5s ease";
  60570. this._loadingDiv.style.pointerEvents = "none";
  60571. // Loading text
  60572. this._loadingTextDiv = document.createElement("div");
  60573. this._loadingTextDiv.style.position = "absolute";
  60574. this._loadingTextDiv.style.left = "0";
  60575. this._loadingTextDiv.style.top = "50%";
  60576. this._loadingTextDiv.style.marginTop = "80px";
  60577. this._loadingTextDiv.style.width = "100%";
  60578. this._loadingTextDiv.style.height = "20px";
  60579. this._loadingTextDiv.style.fontFamily = "Arial";
  60580. this._loadingTextDiv.style.fontSize = "14px";
  60581. this._loadingTextDiv.style.color = "white";
  60582. this._loadingTextDiv.style.textAlign = "center";
  60583. this._loadingTextDiv.innerHTML = "Loading";
  60584. this._loadingDiv.appendChild(this._loadingTextDiv);
  60585. //set the predefined text
  60586. this._loadingTextDiv.innerHTML = this._loadingText;
  60587. // Generating keyframes
  60588. var style = document.createElement('style');
  60589. style.type = 'text/css';
  60590. 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 }";
  60591. style.innerHTML = keyFrames;
  60592. document.getElementsByTagName('head')[0].appendChild(style);
  60593. // Loading img
  60594. var imgBack = new Image();
  60595. 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";
  60596. imgBack.style.position = "absolute";
  60597. imgBack.style.left = "50%";
  60598. imgBack.style.top = "50%";
  60599. imgBack.style.marginLeft = "-60px";
  60600. imgBack.style.marginTop = "-60px";
  60601. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  60602. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  60603. imgBack.style.transformOrigin = "50% 50%";
  60604. imgBack.style.webkitTransformOrigin = "50% 50%";
  60605. this._loadingDiv.appendChild(imgBack);
  60606. this._resizeLoadingUI();
  60607. window.addEventListener("resize", this._resizeLoadingUI);
  60608. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60609. document.body.appendChild(this._loadingDiv);
  60610. this._loadingDiv.style.opacity = "1";
  60611. };
  60612. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  60613. var _this = this;
  60614. if (!this._loadingDiv) {
  60615. return;
  60616. }
  60617. var onTransitionEnd = function () {
  60618. if (!_this._loadingDiv) {
  60619. return;
  60620. }
  60621. document.body.removeChild(_this._loadingDiv);
  60622. window.removeEventListener("resize", _this._resizeLoadingUI);
  60623. _this._loadingDiv = null;
  60624. };
  60625. this._loadingDiv.style.opacity = "0";
  60626. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  60627. };
  60628. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  60629. set: function (text) {
  60630. this._loadingText = text;
  60631. if (this._loadingTextDiv) {
  60632. this._loadingTextDiv.innerHTML = this._loadingText;
  60633. }
  60634. },
  60635. enumerable: true,
  60636. configurable: true
  60637. });
  60638. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  60639. get: function () {
  60640. return this._loadingDivBackgroundColor;
  60641. },
  60642. set: function (color) {
  60643. this._loadingDivBackgroundColor = color;
  60644. if (!this._loadingDiv) {
  60645. return;
  60646. }
  60647. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60648. },
  60649. enumerable: true,
  60650. configurable: true
  60651. });
  60652. return DefaultLoadingScreen;
  60653. }());
  60654. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  60655. })(BABYLON || (BABYLON = {}));
  60656. //# sourceMappingURL=babylon.loadingScreen.js.map
  60657. var BABYLON;
  60658. (function (BABYLON) {
  60659. var SceneLoaderProgressEvent = /** @class */ (function () {
  60660. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  60661. this.lengthComputable = lengthComputable;
  60662. this.loaded = loaded;
  60663. this.total = total;
  60664. }
  60665. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  60666. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  60667. };
  60668. return SceneLoaderProgressEvent;
  60669. }());
  60670. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  60671. var SceneLoader = /** @class */ (function () {
  60672. function SceneLoader() {
  60673. }
  60674. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  60675. get: function () {
  60676. return 0;
  60677. },
  60678. enumerable: true,
  60679. configurable: true
  60680. });
  60681. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  60682. get: function () {
  60683. return 1;
  60684. },
  60685. enumerable: true,
  60686. configurable: true
  60687. });
  60688. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  60689. get: function () {
  60690. return 2;
  60691. },
  60692. enumerable: true,
  60693. configurable: true
  60694. });
  60695. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  60696. get: function () {
  60697. return 3;
  60698. },
  60699. enumerable: true,
  60700. configurable: true
  60701. });
  60702. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  60703. get: function () {
  60704. return SceneLoader._ForceFullSceneLoadingForIncremental;
  60705. },
  60706. set: function (value) {
  60707. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  60708. },
  60709. enumerable: true,
  60710. configurable: true
  60711. });
  60712. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  60713. get: function () {
  60714. return SceneLoader._ShowLoadingScreen;
  60715. },
  60716. set: function (value) {
  60717. SceneLoader._ShowLoadingScreen = value;
  60718. },
  60719. enumerable: true,
  60720. configurable: true
  60721. });
  60722. Object.defineProperty(SceneLoader, "loggingLevel", {
  60723. get: function () {
  60724. return SceneLoader._loggingLevel;
  60725. },
  60726. set: function (value) {
  60727. SceneLoader._loggingLevel = value;
  60728. },
  60729. enumerable: true,
  60730. configurable: true
  60731. });
  60732. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  60733. get: function () {
  60734. return SceneLoader._CleanBoneMatrixWeights;
  60735. },
  60736. set: function (value) {
  60737. SceneLoader._CleanBoneMatrixWeights = value;
  60738. },
  60739. enumerable: true,
  60740. configurable: true
  60741. });
  60742. SceneLoader._getDefaultPlugin = function () {
  60743. return SceneLoader._registeredPlugins[".babylon"];
  60744. };
  60745. SceneLoader._getPluginForExtension = function (extension) {
  60746. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  60747. if (registeredPlugin) {
  60748. return registeredPlugin;
  60749. }
  60750. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  60751. return SceneLoader._getDefaultPlugin();
  60752. };
  60753. SceneLoader._getPluginForDirectLoad = function (data) {
  60754. for (var extension in SceneLoader._registeredPlugins) {
  60755. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  60756. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  60757. return SceneLoader._registeredPlugins[extension];
  60758. }
  60759. }
  60760. return SceneLoader._getDefaultPlugin();
  60761. };
  60762. SceneLoader._getPluginForFilename = function (sceneFilename) {
  60763. if (sceneFilename.name) {
  60764. sceneFilename = sceneFilename.name;
  60765. }
  60766. var queryStringPosition = sceneFilename.indexOf("?");
  60767. if (queryStringPosition !== -1) {
  60768. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  60769. }
  60770. var dotPosition = sceneFilename.lastIndexOf(".");
  60771. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  60772. return SceneLoader._getPluginForExtension(extension);
  60773. };
  60774. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  60775. SceneLoader._getDirectLoad = function (sceneFilename) {
  60776. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  60777. return sceneFilename.substr(5);
  60778. }
  60779. return null;
  60780. };
  60781. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  60782. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  60783. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  60784. var plugin;
  60785. if (registeredPlugin.plugin.createPlugin) {
  60786. plugin = registeredPlugin.plugin.createPlugin();
  60787. }
  60788. else {
  60789. plugin = registeredPlugin.plugin;
  60790. }
  60791. var useArrayBuffer = registeredPlugin.isBinary;
  60792. var database;
  60793. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  60794. var dataCallback = function (data, responseURL) {
  60795. if (scene.isDisposed) {
  60796. onError("Scene has been disposed");
  60797. return;
  60798. }
  60799. scene.database = database;
  60800. onSuccess(plugin, data, responseURL);
  60801. };
  60802. var request = null;
  60803. var pluginDisposed = false;
  60804. var onDisposeObservable = plugin.onDisposeObservable;
  60805. if (onDisposeObservable) {
  60806. onDisposeObservable.add(function () {
  60807. pluginDisposed = true;
  60808. if (request) {
  60809. request.abort();
  60810. request = null;
  60811. }
  60812. onDispose();
  60813. });
  60814. }
  60815. var manifestChecked = function () {
  60816. if (pluginDisposed) {
  60817. return;
  60818. }
  60819. var url = rootUrl + sceneFilename;
  60820. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  60821. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  60822. } : undefined, database, useArrayBuffer, function (request, exception) {
  60823. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  60824. });
  60825. };
  60826. if (directLoad) {
  60827. dataCallback(directLoad);
  60828. return plugin;
  60829. }
  60830. if (rootUrl.indexOf("file:") === -1) {
  60831. if (scene.getEngine().enableOfflineSupport) {
  60832. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  60833. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  60834. }
  60835. else {
  60836. manifestChecked();
  60837. }
  60838. }
  60839. else {
  60840. var fileOrString = sceneFilename;
  60841. if (fileOrString.name) {
  60842. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  60843. }
  60844. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  60845. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  60846. }
  60847. else {
  60848. onError("Unable to find file named " + sceneFilename);
  60849. }
  60850. }
  60851. return plugin;
  60852. };
  60853. // Public functions
  60854. SceneLoader.GetPluginForExtension = function (extension) {
  60855. return SceneLoader._getPluginForExtension(extension).plugin;
  60856. };
  60857. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  60858. return !!SceneLoader._registeredPlugins[extension];
  60859. };
  60860. SceneLoader.RegisterPlugin = function (plugin) {
  60861. if (typeof plugin.extensions === "string") {
  60862. var extension = plugin.extensions;
  60863. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60864. plugin: plugin,
  60865. isBinary: false
  60866. };
  60867. }
  60868. else {
  60869. var extensions = plugin.extensions;
  60870. Object.keys(extensions).forEach(function (extension) {
  60871. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60872. plugin: plugin,
  60873. isBinary: extensions[extension].isBinary
  60874. };
  60875. });
  60876. }
  60877. };
  60878. /**
  60879. * Import meshes into a scene
  60880. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60881. * @param rootUrl a string that defines the root url for scene and resources
  60882. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60883. * @param scene the instance of BABYLON.Scene to append to
  60884. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  60885. * @param onProgress a callback with a progress event for each file being loaded
  60886. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60887. * @param pluginExtension the extension used to determine the plugin
  60888. * @returns The loaded plugin
  60889. */
  60890. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60891. if (onSuccess === void 0) { onSuccess = null; }
  60892. if (onProgress === void 0) { onProgress = null; }
  60893. if (onError === void 0) { onError = null; }
  60894. if (pluginExtension === void 0) { pluginExtension = null; }
  60895. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60896. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60897. return null;
  60898. }
  60899. var loadingToken = {};
  60900. scene._addPendingData(loadingToken);
  60901. var disposeHandler = function () {
  60902. scene._removePendingData(loadingToken);
  60903. };
  60904. var errorHandler = function (message, exception) {
  60905. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  60906. if (onError) {
  60907. onError(scene, errorMessage, exception);
  60908. }
  60909. else {
  60910. BABYLON.Tools.Error(errorMessage);
  60911. // should the exception be thrown?
  60912. }
  60913. disposeHandler();
  60914. };
  60915. var progressHandler = onProgress ? function (event) {
  60916. try {
  60917. onProgress(event);
  60918. }
  60919. catch (e) {
  60920. errorHandler("Error in onProgress callback", e);
  60921. }
  60922. } : undefined;
  60923. var successHandler = function (meshes, particleSystems, skeletons) {
  60924. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  60925. if (onSuccess) {
  60926. try {
  60927. onSuccess(meshes, particleSystems, skeletons);
  60928. }
  60929. catch (e) {
  60930. errorHandler("Error in onSuccess callback", e);
  60931. }
  60932. }
  60933. scene._removePendingData(loadingToken);
  60934. };
  60935. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60936. if (plugin.rewriteRootURL) {
  60937. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  60938. }
  60939. if (sceneFilename === "") {
  60940. if (sceneFilename === "") {
  60941. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60942. }
  60943. }
  60944. if (plugin.importMesh) {
  60945. var syncedPlugin = plugin;
  60946. var meshes = new Array();
  60947. var particleSystems = new Array();
  60948. var skeletons = new Array();
  60949. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  60950. return;
  60951. }
  60952. scene.loadingPluginName = plugin.name;
  60953. successHandler(meshes, particleSystems, skeletons);
  60954. }
  60955. else {
  60956. var asyncedPlugin = plugin;
  60957. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  60958. scene.loadingPluginName = plugin.name;
  60959. successHandler(result.meshes, result.particleSystems, result.skeletons);
  60960. }).catch(function (error) {
  60961. errorHandler(error.message, error);
  60962. });
  60963. }
  60964. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60965. };
  60966. /**
  60967. * Import meshes into a scene
  60968. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60969. * @param rootUrl a string that defines the root url for scene and resources
  60970. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60971. * @param scene the instance of BABYLON.Scene to append to
  60972. * @param onProgress a callback with a progress event for each file being loaded
  60973. * @param pluginExtension the extension used to determine the plugin
  60974. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  60975. */
  60976. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60977. if (onProgress === void 0) { onProgress = null; }
  60978. if (pluginExtension === void 0) { pluginExtension = null; }
  60979. return new Promise(function (resolve, reject) {
  60980. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  60981. resolve({
  60982. meshes: meshes,
  60983. particleSystems: particleSystems,
  60984. skeletons: skeletons
  60985. });
  60986. }, onProgress, function (scene, message, exception) {
  60987. reject(exception || new Error(message));
  60988. });
  60989. });
  60990. };
  60991. /**
  60992. * Load a scene
  60993. * @param rootUrl a string that defines the root url for scene and resources
  60994. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60995. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60996. * @param onSuccess a callback with the scene when import succeeds
  60997. * @param onProgress a callback with a progress event for each file being loaded
  60998. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60999. * @param pluginExtension the extension used to determine the plugin
  61000. * @returns The loaded plugin
  61001. */
  61002. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  61003. if (onSuccess === void 0) { onSuccess = null; }
  61004. if (onProgress === void 0) { onProgress = null; }
  61005. if (onError === void 0) { onError = null; }
  61006. if (pluginExtension === void 0) { pluginExtension = null; }
  61007. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  61008. };
  61009. /**
  61010. * Load a scene
  61011. * @param rootUrl a string that defines the root url for scene and resources
  61012. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61013. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61014. * @param onProgress a callback with a progress event for each file being loaded
  61015. * @param pluginExtension the extension used to determine the plugin
  61016. * @returns The loaded scene
  61017. */
  61018. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  61019. if (onProgress === void 0) { onProgress = null; }
  61020. if (pluginExtension === void 0) { pluginExtension = null; }
  61021. return new Promise(function (resolve, reject) {
  61022. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  61023. resolve(scene);
  61024. }, onProgress, function (scene, message, exception) {
  61025. reject(exception || new Error(message));
  61026. }, pluginExtension);
  61027. });
  61028. };
  61029. /**
  61030. * Append a scene
  61031. * @param rootUrl a string that defines the root url for scene and resources
  61032. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61033. * @param scene is the instance of BABYLON.Scene to append to
  61034. * @param onSuccess a callback with the scene when import succeeds
  61035. * @param onProgress a callback with a progress event for each file being loaded
  61036. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61037. * @param pluginExtension the extension used to determine the plugin
  61038. * @returns The loaded plugin
  61039. */
  61040. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61041. if (onSuccess === void 0) { onSuccess = null; }
  61042. if (onProgress === void 0) { onProgress = null; }
  61043. if (onError === void 0) { onError = null; }
  61044. if (pluginExtension === void 0) { pluginExtension = null; }
  61045. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61046. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61047. return null;
  61048. }
  61049. if (SceneLoader.ShowLoadingScreen) {
  61050. scene.getEngine().displayLoadingUI();
  61051. }
  61052. var loadingToken = {};
  61053. scene._addPendingData(loadingToken);
  61054. var disposeHandler = function () {
  61055. scene._removePendingData(loadingToken);
  61056. scene.getEngine().hideLoadingUI();
  61057. };
  61058. var errorHandler = function (message, exception) {
  61059. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61060. if (onError) {
  61061. onError(scene, errorMessage, exception);
  61062. }
  61063. else {
  61064. BABYLON.Tools.Error(errorMessage);
  61065. // should the exception be thrown?
  61066. }
  61067. disposeHandler();
  61068. };
  61069. var progressHandler = onProgress ? function (event) {
  61070. try {
  61071. onProgress(event);
  61072. }
  61073. catch (e) {
  61074. errorHandler("Error in onProgress callback", e);
  61075. }
  61076. } : undefined;
  61077. var successHandler = function () {
  61078. if (onSuccess) {
  61079. try {
  61080. onSuccess(scene);
  61081. }
  61082. catch (e) {
  61083. errorHandler("Error in onSuccess callback", e);
  61084. }
  61085. }
  61086. scene._removePendingData(loadingToken);
  61087. };
  61088. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61089. if (sceneFilename === "") {
  61090. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61091. }
  61092. if (plugin.load) {
  61093. var syncedPlugin = plugin;
  61094. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  61095. return;
  61096. }
  61097. scene.loadingPluginName = plugin.name;
  61098. successHandler();
  61099. }
  61100. else {
  61101. var asyncedPlugin = plugin;
  61102. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  61103. scene.loadingPluginName = plugin.name;
  61104. successHandler();
  61105. }).catch(function (error) {
  61106. errorHandler(error.message, error);
  61107. });
  61108. }
  61109. if (SceneLoader.ShowLoadingScreen) {
  61110. scene.executeWhenReady(function () {
  61111. scene.getEngine().hideLoadingUI();
  61112. });
  61113. }
  61114. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61115. };
  61116. /**
  61117. * Append a scene
  61118. * @param rootUrl a string that defines the root url for scene and resources
  61119. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61120. * @param scene is the instance of BABYLON.Scene to append to
  61121. * @param onProgress a callback with a progress event for each file being loaded
  61122. * @param pluginExtension the extension used to determine the plugin
  61123. * @returns The given scene
  61124. */
  61125. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61126. if (onProgress === void 0) { onProgress = null; }
  61127. if (pluginExtension === void 0) { pluginExtension = null; }
  61128. return new Promise(function (resolve, reject) {
  61129. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  61130. resolve(scene);
  61131. }, onProgress, function (scene, message, exception) {
  61132. reject(exception || new Error(message));
  61133. }, pluginExtension);
  61134. });
  61135. };
  61136. /**
  61137. * Load a scene into an asset container
  61138. * @param rootUrl a string that defines the root url for scene and resources
  61139. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61140. * @param scene is the instance of BABYLON.Scene to append to
  61141. * @param onSuccess a callback with the scene when import succeeds
  61142. * @param onProgress a callback with a progress event for each file being loaded
  61143. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61144. * @param pluginExtension the extension used to determine the plugin
  61145. * @returns The loaded plugin
  61146. */
  61147. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61148. if (onSuccess === void 0) { onSuccess = null; }
  61149. if (onProgress === void 0) { onProgress = null; }
  61150. if (onError === void 0) { onError = null; }
  61151. if (pluginExtension === void 0) { pluginExtension = null; }
  61152. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61153. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61154. return null;
  61155. }
  61156. var loadingToken = {};
  61157. scene._addPendingData(loadingToken);
  61158. var disposeHandler = function () {
  61159. scene._removePendingData(loadingToken);
  61160. };
  61161. var errorHandler = function (message, exception) {
  61162. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61163. if (onError) {
  61164. onError(scene, errorMessage, exception);
  61165. }
  61166. else {
  61167. BABYLON.Tools.Error(errorMessage);
  61168. // should the exception be thrown?
  61169. }
  61170. disposeHandler();
  61171. };
  61172. var progressHandler = onProgress ? function (event) {
  61173. try {
  61174. onProgress(event);
  61175. }
  61176. catch (e) {
  61177. errorHandler("Error in onProgress callback", e);
  61178. }
  61179. } : undefined;
  61180. var successHandler = function (assets) {
  61181. if (onSuccess) {
  61182. try {
  61183. onSuccess(assets);
  61184. }
  61185. catch (e) {
  61186. errorHandler("Error in onSuccess callback", e);
  61187. }
  61188. }
  61189. scene._removePendingData(loadingToken);
  61190. };
  61191. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61192. if (plugin.loadAssetContainer) {
  61193. var syncedPlugin = plugin;
  61194. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  61195. if (!assetContainer) {
  61196. return;
  61197. }
  61198. scene.loadingPluginName = plugin.name;
  61199. successHandler(assetContainer);
  61200. }
  61201. else if (plugin.loadAssetContainerAsync) {
  61202. var asyncedPlugin = plugin;
  61203. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  61204. scene.loadingPluginName = plugin.name;
  61205. successHandler(assetContainer);
  61206. }).catch(function (error) {
  61207. errorHandler(error.message, error);
  61208. });
  61209. }
  61210. else {
  61211. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  61212. }
  61213. if (SceneLoader.ShowLoadingScreen) {
  61214. scene.executeWhenReady(function () {
  61215. scene.getEngine().hideLoadingUI();
  61216. });
  61217. }
  61218. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61219. };
  61220. /**
  61221. * Load a scene into an asset container
  61222. * @param rootUrl a string that defines the root url for scene and resources
  61223. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61224. * @param scene is the instance of BABYLON.Scene to append to
  61225. * @param onProgress a callback with a progress event for each file being loaded
  61226. * @param pluginExtension the extension used to determine the plugin
  61227. * @returns The loaded asset container
  61228. */
  61229. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61230. if (onProgress === void 0) { onProgress = null; }
  61231. if (pluginExtension === void 0) { pluginExtension = null; }
  61232. return new Promise(function (resolve, reject) {
  61233. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  61234. resolve(assetContainer);
  61235. }, onProgress, function (scene, message, exception) {
  61236. reject(exception || new Error(message));
  61237. }, pluginExtension);
  61238. });
  61239. };
  61240. // Flags
  61241. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  61242. SceneLoader._ShowLoadingScreen = true;
  61243. SceneLoader._CleanBoneMatrixWeights = false;
  61244. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  61245. // Members
  61246. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  61247. SceneLoader._registeredPlugins = {};
  61248. return SceneLoader;
  61249. }());
  61250. BABYLON.SceneLoader = SceneLoader;
  61251. ;
  61252. })(BABYLON || (BABYLON = {}));
  61253. //# sourceMappingURL=babylon.sceneLoader.js.map
  61254. var BABYLON;
  61255. (function (BABYLON) {
  61256. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  61257. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61258. var parsedMaterial = parsedData.materials[index];
  61259. if (parsedMaterial.id === id) {
  61260. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61261. }
  61262. }
  61263. return null;
  61264. };
  61265. var isDescendantOf = function (mesh, names, hierarchyIds) {
  61266. for (var i in names) {
  61267. if (mesh.name === names[i]) {
  61268. hierarchyIds.push(mesh.id);
  61269. return true;
  61270. }
  61271. }
  61272. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  61273. hierarchyIds.push(mesh.id);
  61274. return true;
  61275. }
  61276. return false;
  61277. };
  61278. var logOperation = function (operation, producer) {
  61279. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  61280. };
  61281. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  61282. if (addToScene === void 0) { addToScene = false; }
  61283. var container = new BABYLON.AssetContainer(scene);
  61284. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61285. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61286. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61287. // and avoid problems with multiple concurrent .babylon loads.
  61288. var log = "importScene has failed JSON parse";
  61289. try {
  61290. var parsedData = JSON.parse(data);
  61291. log = "";
  61292. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61293. var index;
  61294. var cache;
  61295. // Lights
  61296. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  61297. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  61298. var parsedLight = parsedData.lights[index];
  61299. var light = BABYLON.Light.Parse(parsedLight, scene);
  61300. if (light) {
  61301. container.lights.push(light);
  61302. log += (index === 0 ? "\n\tLights:" : "");
  61303. log += "\n\t\t" + light.toString(fullDetails);
  61304. }
  61305. }
  61306. }
  61307. // Animations
  61308. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  61309. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  61310. var parsedAnimation = parsedData.animations[index];
  61311. var animation = BABYLON.Animation.Parse(parsedAnimation);
  61312. scene.animations.push(animation);
  61313. container.animations.push(animation);
  61314. log += (index === 0 ? "\n\tAnimations:" : "");
  61315. log += "\n\t\t" + animation.toString(fullDetails);
  61316. }
  61317. }
  61318. // Materials
  61319. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  61320. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61321. var parsedMaterial = parsedData.materials[index];
  61322. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61323. container.materials.push(mat);
  61324. log += (index === 0 ? "\n\tMaterials:" : "");
  61325. log += "\n\t\t" + mat.toString(fullDetails);
  61326. }
  61327. }
  61328. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61329. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  61330. var parsedMultiMaterial = parsedData.multiMaterials[index];
  61331. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61332. container.multiMaterials.push(mmat);
  61333. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  61334. log += "\n\t\t" + mmat.toString(fullDetails);
  61335. }
  61336. }
  61337. // Morph targets
  61338. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  61339. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  61340. var managerData = _a[_i];
  61341. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  61342. }
  61343. }
  61344. // Skeletons
  61345. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61346. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  61347. var parsedSkeleton = parsedData.skeletons[index];
  61348. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61349. container.skeletons.push(skeleton);
  61350. log += (index === 0 ? "\n\tSkeletons:" : "");
  61351. log += "\n\t\t" + skeleton.toString(fullDetails);
  61352. }
  61353. }
  61354. // Geometries
  61355. var geometries = parsedData.geometries;
  61356. if (geometries !== undefined && geometries !== null) {
  61357. var addedGeometry = new Array();
  61358. // Boxes
  61359. var boxes = geometries.boxes;
  61360. if (boxes !== undefined && boxes !== null) {
  61361. for (index = 0, cache = boxes.length; index < cache; index++) {
  61362. var parsedBox = boxes[index];
  61363. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  61364. }
  61365. }
  61366. // Spheres
  61367. var spheres = geometries.spheres;
  61368. if (spheres !== undefined && spheres !== null) {
  61369. for (index = 0, cache = spheres.length; index < cache; index++) {
  61370. var parsedSphere = spheres[index];
  61371. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  61372. }
  61373. }
  61374. // Cylinders
  61375. var cylinders = geometries.cylinders;
  61376. if (cylinders !== undefined && cylinders !== null) {
  61377. for (index = 0, cache = cylinders.length; index < cache; index++) {
  61378. var parsedCylinder = cylinders[index];
  61379. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  61380. }
  61381. }
  61382. // Toruses
  61383. var toruses = geometries.toruses;
  61384. if (toruses !== undefined && toruses !== null) {
  61385. for (index = 0, cache = toruses.length; index < cache; index++) {
  61386. var parsedTorus = toruses[index];
  61387. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  61388. }
  61389. }
  61390. // Grounds
  61391. var grounds = geometries.grounds;
  61392. if (grounds !== undefined && grounds !== null) {
  61393. for (index = 0, cache = grounds.length; index < cache; index++) {
  61394. var parsedGround = grounds[index];
  61395. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  61396. }
  61397. }
  61398. // Planes
  61399. var planes = geometries.planes;
  61400. if (planes !== undefined && planes !== null) {
  61401. for (index = 0, cache = planes.length; index < cache; index++) {
  61402. var parsedPlane = planes[index];
  61403. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  61404. }
  61405. }
  61406. // TorusKnots
  61407. var torusKnots = geometries.torusKnots;
  61408. if (torusKnots !== undefined && torusKnots !== null) {
  61409. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  61410. var parsedTorusKnot = torusKnots[index];
  61411. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  61412. }
  61413. }
  61414. // VertexData
  61415. var vertexData = geometries.vertexData;
  61416. if (vertexData !== undefined && vertexData !== null) {
  61417. for (index = 0, cache = vertexData.length; index < cache; index++) {
  61418. var parsedVertexData = vertexData[index];
  61419. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  61420. }
  61421. }
  61422. addedGeometry.forEach(function (g) {
  61423. if (g) {
  61424. container.geometries.push(g);
  61425. }
  61426. });
  61427. }
  61428. // Transform nodes
  61429. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  61430. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  61431. var parsedTransformNode = parsedData.transformNodes[index];
  61432. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  61433. container.transformNodes.push(node);
  61434. }
  61435. }
  61436. // Meshes
  61437. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61438. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61439. var parsedMesh = parsedData.meshes[index];
  61440. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61441. container.meshes.push(mesh);
  61442. log += (index === 0 ? "\n\tMeshes:" : "");
  61443. log += "\n\t\t" + mesh.toString(fullDetails);
  61444. }
  61445. }
  61446. // Cameras
  61447. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  61448. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  61449. var parsedCamera = parsedData.cameras[index];
  61450. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  61451. container.cameras.push(camera);
  61452. log += (index === 0 ? "\n\tCameras:" : "");
  61453. log += "\n\t\t" + camera.toString(fullDetails);
  61454. }
  61455. }
  61456. // Browsing all the graph to connect the dots
  61457. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  61458. var camera = scene.cameras[index];
  61459. if (camera._waitingParentId) {
  61460. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  61461. camera._waitingParentId = null;
  61462. }
  61463. }
  61464. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61465. var light_1 = scene.lights[index];
  61466. if (light_1 && light_1._waitingParentId) {
  61467. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  61468. light_1._waitingParentId = null;
  61469. }
  61470. }
  61471. // Sounds
  61472. // TODO: add sound
  61473. var loadedSounds = [];
  61474. var loadedSound;
  61475. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  61476. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  61477. var parsedSound = parsedData.sounds[index];
  61478. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61479. if (!parsedSound.url)
  61480. parsedSound.url = parsedSound.name;
  61481. if (!loadedSounds[parsedSound.url]) {
  61482. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  61483. loadedSounds[parsedSound.url] = loadedSound;
  61484. container.sounds.push(loadedSound);
  61485. }
  61486. else {
  61487. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  61488. }
  61489. }
  61490. else {
  61491. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  61492. }
  61493. }
  61494. }
  61495. loadedSounds = [];
  61496. // Connect parents & children and parse actions
  61497. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  61498. var transformNode = scene.transformNodes[index];
  61499. if (transformNode._waitingParentId) {
  61500. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  61501. transformNode._waitingParentId = null;
  61502. }
  61503. }
  61504. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61505. var mesh = scene.meshes[index];
  61506. if (mesh._waitingParentId) {
  61507. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  61508. mesh._waitingParentId = null;
  61509. }
  61510. if (mesh._waitingActions) {
  61511. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  61512. mesh._waitingActions = null;
  61513. }
  61514. }
  61515. // freeze world matrix application
  61516. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61517. var currentMesh = scene.meshes[index];
  61518. if (currentMesh._waitingFreezeWorldMatrix) {
  61519. currentMesh.freezeWorldMatrix();
  61520. currentMesh._waitingFreezeWorldMatrix = null;
  61521. }
  61522. else {
  61523. currentMesh.computeWorldMatrix(true);
  61524. }
  61525. }
  61526. // Particles Systems
  61527. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61528. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61529. var parsedParticleSystem = parsedData.particleSystems[index];
  61530. if (parsedParticleSystem.activeParticleCount) {
  61531. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61532. container.particleSystems.push(ps);
  61533. }
  61534. else {
  61535. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61536. container.particleSystems.push(ps);
  61537. }
  61538. }
  61539. }
  61540. // Lens flares
  61541. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  61542. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  61543. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  61544. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  61545. container.lensFlareSystems.push(lf);
  61546. }
  61547. }
  61548. // Shadows
  61549. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  61550. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  61551. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  61552. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  61553. container.shadowGenerators.push(sg);
  61554. }
  61555. }
  61556. // Lights exclusions / inclusions
  61557. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61558. var light_2 = scene.lights[index];
  61559. // Excluded check
  61560. if (light_2._excludedMeshesIds.length > 0) {
  61561. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  61562. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  61563. if (excludedMesh) {
  61564. light_2.excludedMeshes.push(excludedMesh);
  61565. }
  61566. }
  61567. light_2._excludedMeshesIds = [];
  61568. }
  61569. // Included check
  61570. if (light_2._includedOnlyMeshesIds.length > 0) {
  61571. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  61572. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  61573. if (includedOnlyMesh) {
  61574. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  61575. }
  61576. }
  61577. light_2._includedOnlyMeshesIds = [];
  61578. }
  61579. }
  61580. // Actions (scene)
  61581. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  61582. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  61583. }
  61584. if (!addToScene) {
  61585. container.removeAllFromScene();
  61586. }
  61587. }
  61588. catch (err) {
  61589. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  61590. if (onError) {
  61591. onError(msg, err);
  61592. }
  61593. else {
  61594. BABYLON.Tools.Log(msg);
  61595. throw err;
  61596. }
  61597. }
  61598. finally {
  61599. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61600. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61601. }
  61602. }
  61603. return container;
  61604. };
  61605. BABYLON.SceneLoader.RegisterPlugin({
  61606. name: "babylon.js",
  61607. extensions: ".babylon",
  61608. canDirectLoad: function (data) {
  61609. if (data.indexOf("babylon") !== -1) {
  61610. return true;
  61611. }
  61612. return false;
  61613. },
  61614. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  61615. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61616. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61617. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61618. // and avoid problems with multiple concurrent .babylon loads.
  61619. var log = "importMesh has failed JSON parse";
  61620. try {
  61621. var parsedData = JSON.parse(data);
  61622. log = "";
  61623. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61624. if (!meshesNames) {
  61625. meshesNames = null;
  61626. }
  61627. else if (!Array.isArray(meshesNames)) {
  61628. meshesNames = [meshesNames];
  61629. }
  61630. var hierarchyIds = new Array();
  61631. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61632. var loadedSkeletonsIds = [];
  61633. var loadedMaterialsIds = [];
  61634. var index;
  61635. var cache;
  61636. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61637. var parsedMesh = parsedData.meshes[index];
  61638. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  61639. if (meshesNames !== null) {
  61640. // Remove found mesh name from list.
  61641. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  61642. }
  61643. //Geometry?
  61644. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  61645. //does the file contain geometries?
  61646. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  61647. //find the correct geometry and add it to the scene
  61648. var found = false;
  61649. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  61650. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  61651. return;
  61652. }
  61653. else {
  61654. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  61655. if (parsedGeometryData.id === parsedMesh.geometryId) {
  61656. switch (geometryType) {
  61657. case "boxes":
  61658. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  61659. break;
  61660. case "spheres":
  61661. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  61662. break;
  61663. case "cylinders":
  61664. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  61665. break;
  61666. case "toruses":
  61667. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  61668. break;
  61669. case "grounds":
  61670. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  61671. break;
  61672. case "planes":
  61673. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  61674. break;
  61675. case "torusKnots":
  61676. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  61677. break;
  61678. case "vertexData":
  61679. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  61680. break;
  61681. }
  61682. found = true;
  61683. }
  61684. });
  61685. }
  61686. });
  61687. if (found === false) {
  61688. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  61689. }
  61690. }
  61691. }
  61692. // Material ?
  61693. if (parsedMesh.materialId) {
  61694. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  61695. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61696. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  61697. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  61698. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  61699. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  61700. var subMatId = parsedMultiMaterial.materials[matIndex];
  61701. loadedMaterialsIds.push(subMatId);
  61702. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  61703. if (mat) {
  61704. log += "\n\tMaterial " + mat.toString(fullDetails);
  61705. }
  61706. }
  61707. loadedMaterialsIds.push(parsedMultiMaterial.id);
  61708. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61709. if (mmat) {
  61710. materialFound = true;
  61711. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  61712. }
  61713. break;
  61714. }
  61715. }
  61716. }
  61717. if (materialFound === false) {
  61718. loadedMaterialsIds.push(parsedMesh.materialId);
  61719. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  61720. if (!mat) {
  61721. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  61722. }
  61723. else {
  61724. log += "\n\tMaterial " + mat.toString(fullDetails);
  61725. }
  61726. }
  61727. }
  61728. // Skeleton ?
  61729. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61730. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  61731. if (skeletonAlreadyLoaded === false) {
  61732. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  61733. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  61734. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  61735. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61736. skeletons.push(skeleton);
  61737. loadedSkeletonsIds.push(parsedSkeleton.id);
  61738. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  61739. }
  61740. }
  61741. }
  61742. }
  61743. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61744. meshes.push(mesh);
  61745. log += "\n\tMesh " + mesh.toString(fullDetails);
  61746. }
  61747. }
  61748. // Connecting parents
  61749. var currentMesh;
  61750. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61751. currentMesh = scene.meshes[index];
  61752. if (currentMesh._waitingParentId) {
  61753. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  61754. currentMesh._waitingParentId = null;
  61755. }
  61756. }
  61757. // freeze and compute world matrix application
  61758. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61759. currentMesh = scene.meshes[index];
  61760. if (currentMesh._waitingFreezeWorldMatrix) {
  61761. currentMesh.freezeWorldMatrix();
  61762. currentMesh._waitingFreezeWorldMatrix = null;
  61763. }
  61764. else {
  61765. currentMesh.computeWorldMatrix(true);
  61766. }
  61767. }
  61768. }
  61769. // Particles
  61770. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61771. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61772. var parsedParticleSystem = parsedData.particleSystems[index];
  61773. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  61774. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  61775. }
  61776. }
  61777. }
  61778. return true;
  61779. }
  61780. catch (err) {
  61781. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  61782. if (onError) {
  61783. onError(msg, err);
  61784. }
  61785. else {
  61786. BABYLON.Tools.Log(msg);
  61787. throw err;
  61788. }
  61789. }
  61790. finally {
  61791. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61792. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61793. }
  61794. }
  61795. return false;
  61796. },
  61797. load: function (scene, data, rootUrl, onError) {
  61798. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61799. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61800. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61801. // and avoid problems with multiple concurrent .babylon loads.
  61802. var log = "importScene has failed JSON parse";
  61803. try {
  61804. var parsedData = JSON.parse(data);
  61805. log = "";
  61806. // Scene
  61807. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  61808. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  61809. }
  61810. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  61811. scene.autoClear = parsedData.autoClear;
  61812. }
  61813. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  61814. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  61815. }
  61816. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  61817. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  61818. }
  61819. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  61820. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  61821. }
  61822. // Fog
  61823. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  61824. scene.fogMode = parsedData.fogMode;
  61825. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  61826. scene.fogStart = parsedData.fogStart;
  61827. scene.fogEnd = parsedData.fogEnd;
  61828. scene.fogDensity = parsedData.fogDensity;
  61829. log += "\tFog mode for scene: ";
  61830. switch (scene.fogMode) {
  61831. // getters not compiling, so using hardcoded
  61832. case 1:
  61833. log += "exp\n";
  61834. break;
  61835. case 2:
  61836. log += "exp2\n";
  61837. break;
  61838. case 3:
  61839. log += "linear\n";
  61840. break;
  61841. }
  61842. }
  61843. //Physics
  61844. if (parsedData.physicsEnabled) {
  61845. var physicsPlugin;
  61846. if (parsedData.physicsEngine === "cannon") {
  61847. physicsPlugin = new BABYLON.CannonJSPlugin();
  61848. }
  61849. else if (parsedData.physicsEngine === "oimo") {
  61850. physicsPlugin = new BABYLON.OimoJSPlugin();
  61851. }
  61852. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  61853. //else - default engine, which is currently oimo
  61854. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  61855. scene.enablePhysics(physicsGravity, physicsPlugin);
  61856. }
  61857. // Metadata
  61858. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  61859. scene.metadata = parsedData.metadata;
  61860. }
  61861. //collisions, if defined. otherwise, default is true
  61862. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  61863. scene.collisionsEnabled = parsedData.collisionsEnabled;
  61864. }
  61865. scene.workerCollisions = !!parsedData.workerCollisions;
  61866. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  61867. if (!container) {
  61868. return false;
  61869. }
  61870. if (parsedData.autoAnimate) {
  61871. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  61872. }
  61873. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  61874. scene.setActiveCameraByID(parsedData.activeCameraID);
  61875. }
  61876. // Environment texture
  61877. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  61878. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  61879. if (parsedData.createDefaultSkybox === true) {
  61880. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  61881. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  61882. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  61883. }
  61884. }
  61885. // Finish
  61886. return true;
  61887. }
  61888. catch (err) {
  61889. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  61890. if (onError) {
  61891. onError(msg, err);
  61892. }
  61893. else {
  61894. BABYLON.Tools.Log(msg);
  61895. throw err;
  61896. }
  61897. }
  61898. finally {
  61899. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61900. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61901. }
  61902. }
  61903. return false;
  61904. },
  61905. loadAssetContainer: function (scene, data, rootUrl, onError) {
  61906. var container = loadAssetContainer(scene, data, rootUrl, onError);
  61907. return container;
  61908. }
  61909. });
  61910. })(BABYLON || (BABYLON = {}));
  61911. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  61912. var BABYLON;
  61913. (function (BABYLON) {
  61914. var FilesInput = /** @class */ (function () {
  61915. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  61916. this.onProcessFileCallback = function () { return true; };
  61917. this._engine = engine;
  61918. this._currentScene = scene;
  61919. this._sceneLoadedCallback = sceneLoadedCallback;
  61920. this._progressCallback = progressCallback;
  61921. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  61922. this._textureLoadingCallback = textureLoadingCallback;
  61923. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  61924. this._onReloadCallback = onReloadCallback;
  61925. this._errorCallback = errorCallback;
  61926. }
  61927. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  61928. var _this = this;
  61929. if (elementToMonitor) {
  61930. this._elementToMonitor = elementToMonitor;
  61931. this._dragEnterHandler = function (e) { _this.drag(e); };
  61932. this._dragOverHandler = function (e) { _this.drag(e); };
  61933. this._dropHandler = function (e) { _this.drop(e); };
  61934. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  61935. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  61936. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  61937. }
  61938. };
  61939. FilesInput.prototype.dispose = function () {
  61940. if (!this._elementToMonitor) {
  61941. return;
  61942. }
  61943. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  61944. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  61945. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  61946. };
  61947. FilesInput.prototype.renderFunction = function () {
  61948. if (this._additionalRenderLoopLogicCallback) {
  61949. this._additionalRenderLoopLogicCallback();
  61950. }
  61951. if (this._currentScene) {
  61952. if (this._textureLoadingCallback) {
  61953. var remaining = this._currentScene.getWaitingItemsCount();
  61954. if (remaining > 0) {
  61955. this._textureLoadingCallback(remaining);
  61956. }
  61957. }
  61958. this._currentScene.render();
  61959. }
  61960. };
  61961. FilesInput.prototype.drag = function (e) {
  61962. e.stopPropagation();
  61963. e.preventDefault();
  61964. };
  61965. FilesInput.prototype.drop = function (eventDrop) {
  61966. eventDrop.stopPropagation();
  61967. eventDrop.preventDefault();
  61968. this.loadFiles(eventDrop);
  61969. };
  61970. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  61971. var _this = this;
  61972. var reader = folder.createReader();
  61973. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  61974. reader.readEntries(function (entries) {
  61975. remaining.count += entries.length;
  61976. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  61977. var entry = entries_1[_i];
  61978. if (entry.isFile) {
  61979. entry.file(function (file) {
  61980. file.correctName = relativePath + file.name;
  61981. files.push(file);
  61982. if (--remaining.count === 0) {
  61983. callback();
  61984. }
  61985. });
  61986. }
  61987. else if (entry.isDirectory) {
  61988. _this._traverseFolder(entry, files, remaining, callback);
  61989. }
  61990. }
  61991. if (--remaining.count) {
  61992. callback();
  61993. }
  61994. });
  61995. };
  61996. FilesInput.prototype._processFiles = function (files) {
  61997. for (var i = 0; i < files.length; i++) {
  61998. var name = files[i].correctName.toLowerCase();
  61999. var extension = name.split('.').pop();
  62000. if (!this.onProcessFileCallback(files[i], name, extension)) {
  62001. continue;
  62002. }
  62003. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  62004. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  62005. this._sceneFileToLoad = files[i];
  62006. }
  62007. else {
  62008. FilesInput.FilesToLoad[name] = files[i];
  62009. }
  62010. }
  62011. };
  62012. FilesInput.prototype.loadFiles = function (event) {
  62013. var _this = this;
  62014. if (this._startingProcessingFilesCallback)
  62015. this._startingProcessingFilesCallback();
  62016. // Handling data transfer via drag'n'drop
  62017. if (event && event.dataTransfer && event.dataTransfer.files) {
  62018. this._filesToLoad = event.dataTransfer.files;
  62019. }
  62020. // Handling files from input files
  62021. if (event && event.target && event.target.files) {
  62022. this._filesToLoad = event.target.files;
  62023. }
  62024. if (this._filesToLoad && this._filesToLoad.length > 0) {
  62025. var files_1 = new Array();
  62026. var folders = [];
  62027. var items = event.dataTransfer ? event.dataTransfer.items : null;
  62028. for (var i = 0; i < this._filesToLoad.length; i++) {
  62029. var fileToLoad = this._filesToLoad[i];
  62030. var name_1 = fileToLoad.name.toLowerCase();
  62031. var entry = void 0;
  62032. fileToLoad.correctName = name_1;
  62033. if (items) {
  62034. var item = items[i];
  62035. if (item.getAsEntry) {
  62036. entry = item.getAsEntry();
  62037. }
  62038. else if (item.webkitGetAsEntry) {
  62039. entry = item.webkitGetAsEntry();
  62040. }
  62041. }
  62042. if (!entry) {
  62043. files_1.push(fileToLoad);
  62044. }
  62045. else {
  62046. if (entry.isDirectory) {
  62047. folders.push(entry);
  62048. }
  62049. else {
  62050. files_1.push(fileToLoad);
  62051. }
  62052. }
  62053. }
  62054. if (folders.length === 0) {
  62055. this._processFiles(files_1);
  62056. this._processReload();
  62057. }
  62058. else {
  62059. var remaining = { count: folders.length };
  62060. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  62061. var folder = folders_1[_i];
  62062. this._traverseFolder(folder, files_1, remaining, function () {
  62063. _this._processFiles(files_1);
  62064. if (remaining.count === 0) {
  62065. _this._processReload();
  62066. }
  62067. });
  62068. }
  62069. }
  62070. }
  62071. };
  62072. FilesInput.prototype._processReload = function () {
  62073. if (this._onReloadCallback) {
  62074. this._onReloadCallback(this._sceneFileToLoad);
  62075. }
  62076. else {
  62077. this.reload();
  62078. }
  62079. };
  62080. FilesInput.prototype.reload = function () {
  62081. var _this = this;
  62082. // If a scene file has been provided
  62083. if (this._sceneFileToLoad) {
  62084. if (this._currentScene) {
  62085. if (BABYLON.Tools.errorsCount > 0) {
  62086. BABYLON.Tools.ClearLogCache();
  62087. }
  62088. this._engine.stopRenderLoop();
  62089. this._currentScene.dispose();
  62090. }
  62091. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  62092. if (_this._progressCallback) {
  62093. _this._progressCallback(progress);
  62094. }
  62095. }).then(function (scene) {
  62096. _this._currentScene = scene;
  62097. if (_this._sceneLoadedCallback) {
  62098. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  62099. }
  62100. // Wait for textures and shaders to be ready
  62101. _this._currentScene.executeWhenReady(function () {
  62102. _this._engine.runRenderLoop(function () {
  62103. _this.renderFunction();
  62104. });
  62105. });
  62106. }).catch(function (error) {
  62107. if (_this._errorCallback) {
  62108. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  62109. }
  62110. });
  62111. }
  62112. else {
  62113. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  62114. }
  62115. };
  62116. FilesInput.FilesToLoad = {};
  62117. return FilesInput;
  62118. }());
  62119. BABYLON.FilesInput = FilesInput;
  62120. })(BABYLON || (BABYLON = {}));
  62121. //# sourceMappingURL=babylon.filesInput.js.map
  62122. var BABYLON;
  62123. (function (BABYLON) {
  62124. /**
  62125. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62126. * The underlying implementation relies on an associative array to ensure the best performances.
  62127. * The value can be anything including 'null' but except 'undefined'
  62128. */
  62129. var StringDictionary = /** @class */ (function () {
  62130. function StringDictionary() {
  62131. this._count = 0;
  62132. this._data = {};
  62133. }
  62134. /**
  62135. * This will clear this dictionary and copy the content from the 'source' one.
  62136. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  62137. * @param source the dictionary to take the content from and copy to this dictionary
  62138. */
  62139. StringDictionary.prototype.copyFrom = function (source) {
  62140. var _this = this;
  62141. this.clear();
  62142. source.forEach(function (t, v) { return _this.add(t, v); });
  62143. };
  62144. /**
  62145. * Get a value based from its key
  62146. * @param key the given key to get the matching value from
  62147. * @return the value if found, otherwise undefined is returned
  62148. */
  62149. StringDictionary.prototype.get = function (key) {
  62150. var val = this._data[key];
  62151. if (val !== undefined) {
  62152. return val;
  62153. }
  62154. return undefined;
  62155. };
  62156. /**
  62157. * Get a value from its key or add it if it doesn't exist.
  62158. * This method will ensure you that a given key/data will be present in the dictionary.
  62159. * @param key the given key to get the matching value from
  62160. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62161. * The factory will only be invoked if there's no data for the given key.
  62162. * @return the value corresponding to the key.
  62163. */
  62164. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62165. var val = this.get(key);
  62166. if (val !== undefined) {
  62167. return val;
  62168. }
  62169. val = factory(key);
  62170. if (val) {
  62171. this.add(key, val);
  62172. }
  62173. return val;
  62174. };
  62175. /**
  62176. * Get a value from its key if present in the dictionary otherwise add it
  62177. * @param key the key to get the value from
  62178. * @param val if there's no such key/value pair in the dictionary add it with this value
  62179. * @return the value corresponding to the key
  62180. */
  62181. StringDictionary.prototype.getOrAdd = function (key, val) {
  62182. var curVal = this.get(key);
  62183. if (curVal !== undefined) {
  62184. return curVal;
  62185. }
  62186. this.add(key, val);
  62187. return val;
  62188. };
  62189. /**
  62190. * Check if there's a given key in the dictionary
  62191. * @param key the key to check for
  62192. * @return true if the key is present, false otherwise
  62193. */
  62194. StringDictionary.prototype.contains = function (key) {
  62195. return this._data[key] !== undefined;
  62196. };
  62197. /**
  62198. * Add a new key and its corresponding value
  62199. * @param key the key to add
  62200. * @param value the value corresponding to the key
  62201. * @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
  62202. */
  62203. StringDictionary.prototype.add = function (key, value) {
  62204. if (this._data[key] !== undefined) {
  62205. return false;
  62206. }
  62207. this._data[key] = value;
  62208. ++this._count;
  62209. return true;
  62210. };
  62211. StringDictionary.prototype.set = function (key, value) {
  62212. if (this._data[key] === undefined) {
  62213. return false;
  62214. }
  62215. this._data[key] = value;
  62216. return true;
  62217. };
  62218. /**
  62219. * Get the element of the given key and remove it from the dictionary
  62220. * @param key
  62221. */
  62222. StringDictionary.prototype.getAndRemove = function (key) {
  62223. var val = this.get(key);
  62224. if (val !== undefined) {
  62225. delete this._data[key];
  62226. --this._count;
  62227. return val;
  62228. }
  62229. return null;
  62230. };
  62231. /**
  62232. * Remove a key/value from the dictionary.
  62233. * @param key the key to remove
  62234. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62235. */
  62236. StringDictionary.prototype.remove = function (key) {
  62237. if (this.contains(key)) {
  62238. delete this._data[key];
  62239. --this._count;
  62240. return true;
  62241. }
  62242. return false;
  62243. };
  62244. /**
  62245. * Clear the whole content of the dictionary
  62246. */
  62247. StringDictionary.prototype.clear = function () {
  62248. this._data = {};
  62249. this._count = 0;
  62250. };
  62251. Object.defineProperty(StringDictionary.prototype, "count", {
  62252. get: function () {
  62253. return this._count;
  62254. },
  62255. enumerable: true,
  62256. configurable: true
  62257. });
  62258. /**
  62259. * Execute a callback on each key/val of the dictionary.
  62260. * Note that you can remove any element in this dictionary in the callback implementation
  62261. * @param callback the callback to execute on a given key/value pair
  62262. */
  62263. StringDictionary.prototype.forEach = function (callback) {
  62264. for (var cur in this._data) {
  62265. var val = this._data[cur];
  62266. callback(cur, val);
  62267. }
  62268. };
  62269. /**
  62270. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62271. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62272. * Note that you can remove any element in this dictionary in the callback implementation
  62273. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62274. */
  62275. StringDictionary.prototype.first = function (callback) {
  62276. for (var cur in this._data) {
  62277. var val = this._data[cur];
  62278. var res = callback(cur, val);
  62279. if (res) {
  62280. return res;
  62281. }
  62282. }
  62283. return null;
  62284. };
  62285. return StringDictionary;
  62286. }());
  62287. BABYLON.StringDictionary = StringDictionary;
  62288. })(BABYLON || (BABYLON = {}));
  62289. //# sourceMappingURL=babylon.stringDictionary.js.map
  62290. var BABYLON;
  62291. (function (BABYLON) {
  62292. var Tags = /** @class */ (function () {
  62293. function Tags() {
  62294. }
  62295. Tags.EnableFor = function (obj) {
  62296. obj._tags = obj._tags || {};
  62297. obj.hasTags = function () {
  62298. return Tags.HasTags(obj);
  62299. };
  62300. obj.addTags = function (tagsString) {
  62301. return Tags.AddTagsTo(obj, tagsString);
  62302. };
  62303. obj.removeTags = function (tagsString) {
  62304. return Tags.RemoveTagsFrom(obj, tagsString);
  62305. };
  62306. obj.matchesTagsQuery = function (tagsQuery) {
  62307. return Tags.MatchesQuery(obj, tagsQuery);
  62308. };
  62309. };
  62310. Tags.DisableFor = function (obj) {
  62311. delete obj._tags;
  62312. delete obj.hasTags;
  62313. delete obj.addTags;
  62314. delete obj.removeTags;
  62315. delete obj.matchesTagsQuery;
  62316. };
  62317. Tags.HasTags = function (obj) {
  62318. if (!obj._tags) {
  62319. return false;
  62320. }
  62321. return !BABYLON.Tools.IsEmpty(obj._tags);
  62322. };
  62323. Tags.GetTags = function (obj, asString) {
  62324. if (asString === void 0) { asString = true; }
  62325. if (!obj._tags) {
  62326. return null;
  62327. }
  62328. if (asString) {
  62329. var tagsArray = [];
  62330. for (var tag in obj._tags) {
  62331. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  62332. tagsArray.push(tag);
  62333. }
  62334. }
  62335. return tagsArray.join(" ");
  62336. }
  62337. else {
  62338. return obj._tags;
  62339. }
  62340. };
  62341. // the tags 'true' and 'false' are reserved and cannot be used as tags
  62342. // a tag cannot start with '||', '&&', and '!'
  62343. // it cannot contain whitespaces
  62344. Tags.AddTagsTo = function (obj, tagsString) {
  62345. if (!tagsString) {
  62346. return;
  62347. }
  62348. if (typeof tagsString !== "string") {
  62349. return;
  62350. }
  62351. var tags = tagsString.split(" ");
  62352. tags.forEach(function (tag, index, array) {
  62353. Tags._AddTagTo(obj, tag);
  62354. });
  62355. };
  62356. Tags._AddTagTo = function (obj, tag) {
  62357. tag = tag.trim();
  62358. if (tag === "" || tag === "true" || tag === "false") {
  62359. return;
  62360. }
  62361. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  62362. return;
  62363. }
  62364. Tags.EnableFor(obj);
  62365. obj._tags[tag] = true;
  62366. };
  62367. Tags.RemoveTagsFrom = function (obj, tagsString) {
  62368. if (!Tags.HasTags(obj)) {
  62369. return;
  62370. }
  62371. var tags = tagsString.split(" ");
  62372. for (var t in tags) {
  62373. Tags._RemoveTagFrom(obj, tags[t]);
  62374. }
  62375. };
  62376. Tags._RemoveTagFrom = function (obj, tag) {
  62377. delete obj._tags[tag];
  62378. };
  62379. Tags.MatchesQuery = function (obj, tagsQuery) {
  62380. if (tagsQuery === undefined) {
  62381. return true;
  62382. }
  62383. if (tagsQuery === "") {
  62384. return Tags.HasTags(obj);
  62385. }
  62386. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  62387. };
  62388. return Tags;
  62389. }());
  62390. BABYLON.Tags = Tags;
  62391. })(BABYLON || (BABYLON = {}));
  62392. //# sourceMappingURL=babylon.tags.js.map
  62393. var BABYLON;
  62394. (function (BABYLON) {
  62395. var AndOrNotEvaluator = /** @class */ (function () {
  62396. function AndOrNotEvaluator() {
  62397. }
  62398. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  62399. if (!query.match(/\([^\(\)]*\)/g)) {
  62400. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  62401. }
  62402. else {
  62403. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  62404. // remove parenthesis
  62405. r = r.slice(1, r.length - 1);
  62406. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  62407. });
  62408. }
  62409. if (query === "true") {
  62410. return true;
  62411. }
  62412. if (query === "false") {
  62413. return false;
  62414. }
  62415. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  62416. };
  62417. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  62418. evaluateCallback = evaluateCallback || (function (r) {
  62419. return r === "true" ? true : false;
  62420. });
  62421. var result;
  62422. var or = parenthesisContent.split("||");
  62423. for (var i in or) {
  62424. if (or.hasOwnProperty(i)) {
  62425. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  62426. var and = ori.split("&&");
  62427. if (and.length > 1) {
  62428. for (var j = 0; j < and.length; ++j) {
  62429. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  62430. if (andj !== "true" && andj !== "false") {
  62431. if (andj[0] === "!") {
  62432. result = !evaluateCallback(andj.substring(1));
  62433. }
  62434. else {
  62435. result = evaluateCallback(andj);
  62436. }
  62437. }
  62438. else {
  62439. result = andj === "true" ? true : false;
  62440. }
  62441. if (!result) {
  62442. ori = "false";
  62443. break;
  62444. }
  62445. }
  62446. }
  62447. if (result || ori === "true") {
  62448. result = true;
  62449. break;
  62450. }
  62451. // result equals false (or undefined)
  62452. if (ori !== "true" && ori !== "false") {
  62453. if (ori[0] === "!") {
  62454. result = !evaluateCallback(ori.substring(1));
  62455. }
  62456. else {
  62457. result = evaluateCallback(ori);
  62458. }
  62459. }
  62460. else {
  62461. result = ori === "true" ? true : false;
  62462. }
  62463. }
  62464. }
  62465. // the whole parenthesis scope is replaced by 'true' or 'false'
  62466. return result ? "true" : "false";
  62467. };
  62468. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  62469. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  62470. // remove whitespaces
  62471. r = r.replace(/[\s]/g, function () { return ""; });
  62472. return r.length % 2 ? "!" : "";
  62473. });
  62474. booleanString = booleanString.trim();
  62475. if (booleanString === "!true") {
  62476. booleanString = "false";
  62477. }
  62478. else if (booleanString === "!false") {
  62479. booleanString = "true";
  62480. }
  62481. return booleanString;
  62482. };
  62483. return AndOrNotEvaluator;
  62484. }());
  62485. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  62486. })(BABYLON || (BABYLON = {}));
  62487. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  62488. var BABYLON;
  62489. (function (BABYLON) {
  62490. var Database = /** @class */ (function () {
  62491. function Database(urlToScene, callbackManifestChecked) {
  62492. // Handling various flavors of prefixed version of IndexedDB
  62493. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  62494. this.callbackManifestChecked = callbackManifestChecked;
  62495. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  62496. this.db = null;
  62497. this._enableSceneOffline = false;
  62498. this._enableTexturesOffline = false;
  62499. this.manifestVersionFound = 0;
  62500. this.mustUpdateRessources = false;
  62501. this.hasReachedQuota = false;
  62502. if (!Database.IDBStorageEnabled) {
  62503. this.callbackManifestChecked(true);
  62504. }
  62505. else {
  62506. this.checkManifestFile();
  62507. }
  62508. }
  62509. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  62510. get: function () {
  62511. return this._enableSceneOffline;
  62512. },
  62513. enumerable: true,
  62514. configurable: true
  62515. });
  62516. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  62517. get: function () {
  62518. return this._enableTexturesOffline;
  62519. },
  62520. enumerable: true,
  62521. configurable: true
  62522. });
  62523. Database.prototype.checkManifestFile = function () {
  62524. var _this = this;
  62525. var noManifestFile = function () {
  62526. _this._enableSceneOffline = false;
  62527. _this._enableTexturesOffline = false;
  62528. _this.callbackManifestChecked(false);
  62529. };
  62530. var timeStampUsed = false;
  62531. var manifestURL = this.currentSceneUrl + ".manifest";
  62532. var xhr = new XMLHttpRequest();
  62533. if (navigator.onLine) {
  62534. // Adding a timestamp to by-pass browsers' cache
  62535. timeStampUsed = true;
  62536. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  62537. }
  62538. xhr.open("GET", manifestURL, true);
  62539. xhr.addEventListener("load", function () {
  62540. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62541. try {
  62542. var manifestFile = JSON.parse(xhr.response);
  62543. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  62544. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  62545. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  62546. _this.manifestVersionFound = manifestFile.version;
  62547. }
  62548. if (_this.callbackManifestChecked) {
  62549. _this.callbackManifestChecked(true);
  62550. }
  62551. }
  62552. catch (ex) {
  62553. noManifestFile();
  62554. }
  62555. }
  62556. else {
  62557. noManifestFile();
  62558. }
  62559. }, false);
  62560. xhr.addEventListener("error", function (event) {
  62561. if (timeStampUsed) {
  62562. timeStampUsed = false;
  62563. // Let's retry without the timeStamp
  62564. // It could fail when coupled with HTML5 Offline API
  62565. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  62566. xhr.open("GET", retryManifestURL, true);
  62567. xhr.send();
  62568. }
  62569. else {
  62570. noManifestFile();
  62571. }
  62572. }, false);
  62573. try {
  62574. xhr.send();
  62575. }
  62576. catch (ex) {
  62577. BABYLON.Tools.Error("Error on XHR send request.");
  62578. this.callbackManifestChecked(false);
  62579. }
  62580. };
  62581. Database.prototype.openAsync = function (successCallback, errorCallback) {
  62582. var _this = this;
  62583. var handleError = function () {
  62584. _this.isSupported = false;
  62585. if (errorCallback)
  62586. errorCallback();
  62587. };
  62588. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  62589. // Your browser doesn't support IndexedDB
  62590. this.isSupported = false;
  62591. if (errorCallback)
  62592. errorCallback();
  62593. }
  62594. else {
  62595. // If the DB hasn't been opened or created yet
  62596. if (!this.db) {
  62597. this.hasReachedQuota = false;
  62598. this.isSupported = true;
  62599. var request = this.idbFactory.open("babylonjs", 1);
  62600. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  62601. request.onerror = function (event) {
  62602. handleError();
  62603. };
  62604. // executes when a version change transaction cannot complete due to other active transactions
  62605. request.onblocked = function (event) {
  62606. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  62607. handleError();
  62608. };
  62609. // DB has been opened successfully
  62610. request.onsuccess = function (event) {
  62611. _this.db = request.result;
  62612. successCallback();
  62613. };
  62614. // Initialization of the DB. Creating Scenes & Textures stores
  62615. request.onupgradeneeded = function (event) {
  62616. _this.db = (event.target).result;
  62617. if (_this.db) {
  62618. try {
  62619. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  62620. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  62621. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  62622. }
  62623. catch (ex) {
  62624. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  62625. handleError();
  62626. }
  62627. }
  62628. };
  62629. }
  62630. else {
  62631. if (successCallback)
  62632. successCallback();
  62633. }
  62634. }
  62635. };
  62636. Database.prototype.loadImageFromDB = function (url, image) {
  62637. var _this = this;
  62638. var completeURL = Database.ReturnFullUrlLocation(url);
  62639. var saveAndLoadImage = function () {
  62640. if (!_this.hasReachedQuota && _this.db !== null) {
  62641. // the texture is not yet in the DB, let's try to save it
  62642. _this._saveImageIntoDBAsync(completeURL, image);
  62643. }
  62644. else {
  62645. image.src = url;
  62646. }
  62647. };
  62648. if (!this.mustUpdateRessources) {
  62649. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  62650. }
  62651. else {
  62652. saveAndLoadImage();
  62653. }
  62654. };
  62655. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  62656. if (this.isSupported && this.db !== null) {
  62657. var texture;
  62658. var transaction = this.db.transaction(["textures"]);
  62659. transaction.onabort = function (event) {
  62660. image.src = url;
  62661. };
  62662. transaction.oncomplete = function (event) {
  62663. var blobTextureURL;
  62664. if (texture) {
  62665. var URL = window.URL || window.webkitURL;
  62666. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  62667. image.onerror = function () {
  62668. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  62669. image.src = url;
  62670. };
  62671. image.src = blobTextureURL;
  62672. }
  62673. else {
  62674. notInDBCallback();
  62675. }
  62676. };
  62677. var getRequest = transaction.objectStore("textures").get(url);
  62678. getRequest.onsuccess = function (event) {
  62679. texture = (event.target).result;
  62680. };
  62681. getRequest.onerror = function (event) {
  62682. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  62683. image.src = url;
  62684. };
  62685. }
  62686. else {
  62687. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62688. image.src = url;
  62689. }
  62690. };
  62691. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  62692. var _this = this;
  62693. if (this.isSupported) {
  62694. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  62695. var generateBlobUrl = function () {
  62696. var blobTextureURL;
  62697. if (blob) {
  62698. var URL = window.URL || window.webkitURL;
  62699. try {
  62700. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  62701. }
  62702. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  62703. catch (ex) {
  62704. blobTextureURL = URL.createObjectURL(blob);
  62705. }
  62706. }
  62707. if (blobTextureURL) {
  62708. image.src = blobTextureURL;
  62709. }
  62710. };
  62711. if (Database.IsUASupportingBlobStorage) {
  62712. var xhr = new XMLHttpRequest(), blob;
  62713. xhr.open("GET", url, true);
  62714. xhr.responseType = "blob";
  62715. xhr.addEventListener("load", function () {
  62716. if (xhr.status === 200 && _this.db) {
  62717. // Blob as response (XHR2)
  62718. blob = xhr.response;
  62719. var transaction = _this.db.transaction(["textures"], "readwrite");
  62720. // the transaction could abort because of a QuotaExceededError error
  62721. transaction.onabort = function (event) {
  62722. try {
  62723. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62724. var srcElement = (event.srcElement || event.target);
  62725. var error = srcElement.error;
  62726. if (error && error.name === "QuotaExceededError") {
  62727. _this.hasReachedQuota = true;
  62728. }
  62729. }
  62730. catch (ex) { }
  62731. generateBlobUrl();
  62732. };
  62733. transaction.oncomplete = function (event) {
  62734. generateBlobUrl();
  62735. };
  62736. var newTexture = { textureUrl: url, data: blob };
  62737. try {
  62738. // Put the blob into the dabase
  62739. var addRequest = transaction.objectStore("textures").put(newTexture);
  62740. addRequest.onsuccess = function (event) {
  62741. };
  62742. addRequest.onerror = function (event) {
  62743. generateBlobUrl();
  62744. };
  62745. }
  62746. catch (ex) {
  62747. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  62748. if (ex.code === 25) {
  62749. Database.IsUASupportingBlobStorage = false;
  62750. }
  62751. image.src = url;
  62752. }
  62753. }
  62754. else {
  62755. image.src = url;
  62756. }
  62757. }, false);
  62758. xhr.addEventListener("error", function (event) {
  62759. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  62760. image.src = url;
  62761. }, false);
  62762. xhr.send();
  62763. }
  62764. else {
  62765. image.src = url;
  62766. }
  62767. }
  62768. else {
  62769. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62770. image.src = url;
  62771. }
  62772. };
  62773. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  62774. var _this = this;
  62775. var updateVersion = function () {
  62776. // the version is not yet in the DB or we need to update it
  62777. _this._saveVersionIntoDBAsync(url, versionLoaded);
  62778. };
  62779. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  62780. };
  62781. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  62782. var _this = this;
  62783. if (this.isSupported && this.db) {
  62784. var version;
  62785. try {
  62786. var transaction = this.db.transaction(["versions"]);
  62787. transaction.oncomplete = function (event) {
  62788. if (version) {
  62789. // If the version in the JSON file is > than the version in DB
  62790. if (_this.manifestVersionFound > version.data) {
  62791. _this.mustUpdateRessources = true;
  62792. updateInDBCallback();
  62793. }
  62794. else {
  62795. callback(version.data);
  62796. }
  62797. }
  62798. else {
  62799. _this.mustUpdateRessources = true;
  62800. updateInDBCallback();
  62801. }
  62802. };
  62803. transaction.onabort = function (event) {
  62804. callback(-1);
  62805. };
  62806. var getRequest = transaction.objectStore("versions").get(url);
  62807. getRequest.onsuccess = function (event) {
  62808. version = (event.target).result;
  62809. };
  62810. getRequest.onerror = function (event) {
  62811. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  62812. callback(-1);
  62813. };
  62814. }
  62815. catch (ex) {
  62816. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  62817. callback(-1);
  62818. }
  62819. }
  62820. else {
  62821. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62822. callback(-1);
  62823. }
  62824. };
  62825. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  62826. var _this = this;
  62827. if (this.isSupported && !this.hasReachedQuota && this.db) {
  62828. try {
  62829. // Open a transaction to the database
  62830. var transaction = this.db.transaction(["versions"], "readwrite");
  62831. // the transaction could abort because of a QuotaExceededError error
  62832. transaction.onabort = function (event) {
  62833. try {
  62834. var error = event.srcElement['error'];
  62835. if (error && error.name === "QuotaExceededError") {
  62836. _this.hasReachedQuota = true;
  62837. }
  62838. }
  62839. catch (ex) { }
  62840. callback(-1);
  62841. };
  62842. transaction.oncomplete = function (event) {
  62843. callback(_this.manifestVersionFound);
  62844. };
  62845. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  62846. // Put the scene into the database
  62847. var addRequest = transaction.objectStore("versions").put(newVersion);
  62848. addRequest.onsuccess = function (event) {
  62849. };
  62850. addRequest.onerror = function (event) {
  62851. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  62852. };
  62853. }
  62854. catch (ex) {
  62855. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  62856. callback(-1);
  62857. }
  62858. }
  62859. else {
  62860. callback(-1);
  62861. }
  62862. };
  62863. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  62864. var _this = this;
  62865. var completeUrl = Database.ReturnFullUrlLocation(url);
  62866. var saveAndLoadFile = function () {
  62867. // the scene is not yet in the DB, let's try to save it
  62868. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  62869. };
  62870. this._checkVersionFromDB(completeUrl, function (version) {
  62871. if (version !== -1) {
  62872. if (!_this.mustUpdateRessources) {
  62873. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  62874. }
  62875. else {
  62876. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  62877. }
  62878. }
  62879. else {
  62880. if (errorCallback) {
  62881. errorCallback();
  62882. }
  62883. }
  62884. });
  62885. };
  62886. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  62887. if (this.isSupported && this.db) {
  62888. var targetStore;
  62889. if (url.indexOf(".babylon") !== -1) {
  62890. targetStore = "scenes";
  62891. }
  62892. else {
  62893. targetStore = "textures";
  62894. }
  62895. var file;
  62896. var transaction = this.db.transaction([targetStore]);
  62897. transaction.oncomplete = function (event) {
  62898. if (file) {
  62899. callback(file.data);
  62900. }
  62901. else {
  62902. notInDBCallback();
  62903. }
  62904. };
  62905. transaction.onabort = function (event) {
  62906. notInDBCallback();
  62907. };
  62908. var getRequest = transaction.objectStore(targetStore).get(url);
  62909. getRequest.onsuccess = function (event) {
  62910. file = (event.target).result;
  62911. };
  62912. getRequest.onerror = function (event) {
  62913. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  62914. notInDBCallback();
  62915. };
  62916. }
  62917. else {
  62918. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62919. callback();
  62920. }
  62921. };
  62922. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  62923. var _this = this;
  62924. if (this.isSupported) {
  62925. var targetStore;
  62926. if (url.indexOf(".babylon") !== -1) {
  62927. targetStore = "scenes";
  62928. }
  62929. else {
  62930. targetStore = "textures";
  62931. }
  62932. // Create XHR
  62933. var xhr = new XMLHttpRequest();
  62934. var fileData;
  62935. xhr.open("GET", url, true);
  62936. if (useArrayBuffer) {
  62937. xhr.responseType = "arraybuffer";
  62938. }
  62939. if (progressCallback) {
  62940. xhr.onprogress = progressCallback;
  62941. }
  62942. xhr.addEventListener("load", function () {
  62943. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  62944. // Blob as response (XHR2)
  62945. //fileData = xhr.responseText;
  62946. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  62947. if (!_this.hasReachedQuota && _this.db) {
  62948. // Open a transaction to the database
  62949. var transaction = _this.db.transaction([targetStore], "readwrite");
  62950. // the transaction could abort because of a QuotaExceededError error
  62951. transaction.onabort = function (event) {
  62952. try {
  62953. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62954. var error = event.srcElement['error'];
  62955. if (error && error.name === "QuotaExceededError") {
  62956. _this.hasReachedQuota = true;
  62957. }
  62958. }
  62959. catch (ex) { }
  62960. callback(fileData);
  62961. };
  62962. transaction.oncomplete = function (event) {
  62963. callback(fileData);
  62964. };
  62965. var newFile;
  62966. if (targetStore === "scenes") {
  62967. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  62968. }
  62969. else {
  62970. newFile = { textureUrl: url, data: fileData };
  62971. }
  62972. try {
  62973. // Put the scene into the database
  62974. var addRequest = transaction.objectStore(targetStore).put(newFile);
  62975. addRequest.onsuccess = function (event) {
  62976. };
  62977. addRequest.onerror = function (event) {
  62978. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  62979. };
  62980. }
  62981. catch (ex) {
  62982. callback(fileData);
  62983. }
  62984. }
  62985. else {
  62986. callback(fileData);
  62987. }
  62988. }
  62989. else {
  62990. callback();
  62991. }
  62992. }, false);
  62993. xhr.addEventListener("error", function (event) {
  62994. BABYLON.Tools.Error("error on XHR request.");
  62995. callback();
  62996. }, false);
  62997. xhr.send();
  62998. }
  62999. else {
  63000. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63001. callback();
  63002. }
  63003. };
  63004. Database.IsUASupportingBlobStorage = true;
  63005. Database.IDBStorageEnabled = true;
  63006. Database.parseURL = function (url) {
  63007. var a = document.createElement('a');
  63008. a.href = url;
  63009. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  63010. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  63011. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  63012. return absLocation;
  63013. };
  63014. Database.ReturnFullUrlLocation = function (url) {
  63015. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  63016. return (Database.parseURL(window.location.href) + url);
  63017. }
  63018. else {
  63019. return url;
  63020. }
  63021. };
  63022. return Database;
  63023. }());
  63024. BABYLON.Database = Database;
  63025. })(BABYLON || (BABYLON = {}));
  63026. //# sourceMappingURL=babylon.database.js.map
  63027. var BABYLON;
  63028. (function (BABYLON) {
  63029. var FresnelParameters = /** @class */ (function () {
  63030. function FresnelParameters() {
  63031. this._isEnabled = true;
  63032. this.leftColor = BABYLON.Color3.White();
  63033. this.rightColor = BABYLON.Color3.Black();
  63034. this.bias = 0;
  63035. this.power = 1;
  63036. }
  63037. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  63038. get: function () {
  63039. return this._isEnabled;
  63040. },
  63041. set: function (value) {
  63042. if (this._isEnabled === value) {
  63043. return;
  63044. }
  63045. this._isEnabled = value;
  63046. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  63047. },
  63048. enumerable: true,
  63049. configurable: true
  63050. });
  63051. FresnelParameters.prototype.clone = function () {
  63052. var newFresnelParameters = new FresnelParameters();
  63053. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  63054. return newFresnelParameters;
  63055. };
  63056. FresnelParameters.prototype.serialize = function () {
  63057. var serializationObject = {};
  63058. serializationObject.isEnabled = this.isEnabled;
  63059. serializationObject.leftColor = this.leftColor;
  63060. serializationObject.rightColor = this.rightColor;
  63061. serializationObject.bias = this.bias;
  63062. serializationObject.power = this.power;
  63063. return serializationObject;
  63064. };
  63065. FresnelParameters.Parse = function (parsedFresnelParameters) {
  63066. var fresnelParameters = new FresnelParameters();
  63067. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  63068. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  63069. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  63070. fresnelParameters.bias = parsedFresnelParameters.bias;
  63071. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  63072. return fresnelParameters;
  63073. };
  63074. return FresnelParameters;
  63075. }());
  63076. BABYLON.FresnelParameters = FresnelParameters;
  63077. })(BABYLON || (BABYLON = {}));
  63078. //# sourceMappingURL=babylon.fresnelParameters.js.map
  63079. var BABYLON;
  63080. (function (BABYLON) {
  63081. var MultiMaterial = /** @class */ (function (_super) {
  63082. __extends(MultiMaterial, _super);
  63083. function MultiMaterial(name, scene) {
  63084. var _this = _super.call(this, name, scene, true) || this;
  63085. scene.multiMaterials.push(_this);
  63086. _this.subMaterials = new Array();
  63087. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  63088. return _this;
  63089. }
  63090. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  63091. get: function () {
  63092. return this._subMaterials;
  63093. },
  63094. set: function (value) {
  63095. this._subMaterials = value;
  63096. this._hookArray(value);
  63097. },
  63098. enumerable: true,
  63099. configurable: true
  63100. });
  63101. MultiMaterial.prototype._hookArray = function (array) {
  63102. var _this = this;
  63103. var oldPush = array.push;
  63104. array.push = function () {
  63105. var items = [];
  63106. for (var _i = 0; _i < arguments.length; _i++) {
  63107. items[_i] = arguments[_i];
  63108. }
  63109. var result = oldPush.apply(array, items);
  63110. _this._markAllSubMeshesAsTexturesDirty();
  63111. return result;
  63112. };
  63113. var oldSplice = array.splice;
  63114. array.splice = function (index, deleteCount) {
  63115. var deleted = oldSplice.apply(array, [index, deleteCount]);
  63116. _this._markAllSubMeshesAsTexturesDirty();
  63117. return deleted;
  63118. };
  63119. };
  63120. // Properties
  63121. MultiMaterial.prototype.getSubMaterial = function (index) {
  63122. if (index < 0 || index >= this.subMaterials.length) {
  63123. return this.getScene().defaultMaterial;
  63124. }
  63125. return this.subMaterials[index];
  63126. };
  63127. MultiMaterial.prototype.getActiveTextures = function () {
  63128. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  63129. if (subMaterial) {
  63130. return subMaterial.getActiveTextures();
  63131. }
  63132. else {
  63133. return [];
  63134. }
  63135. }));
  63136. var _a;
  63137. };
  63138. // Methods
  63139. MultiMaterial.prototype.getClassName = function () {
  63140. return "MultiMaterial";
  63141. };
  63142. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  63143. for (var index = 0; index < this.subMaterials.length; index++) {
  63144. var subMaterial = this.subMaterials[index];
  63145. if (subMaterial) {
  63146. if (subMaterial.storeEffectOnSubMeshes) {
  63147. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  63148. return false;
  63149. }
  63150. continue;
  63151. }
  63152. if (!subMaterial.isReady(mesh)) {
  63153. return false;
  63154. }
  63155. }
  63156. }
  63157. return true;
  63158. };
  63159. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  63160. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  63161. for (var index = 0; index < this.subMaterials.length; index++) {
  63162. var subMaterial = null;
  63163. var current = this.subMaterials[index];
  63164. if (cloneChildren && current) {
  63165. subMaterial = current.clone(name + "-" + current.name);
  63166. }
  63167. else {
  63168. subMaterial = this.subMaterials[index];
  63169. }
  63170. newMultiMaterial.subMaterials.push(subMaterial);
  63171. }
  63172. return newMultiMaterial;
  63173. };
  63174. MultiMaterial.prototype.serialize = function () {
  63175. var serializationObject = {};
  63176. serializationObject.name = this.name;
  63177. serializationObject.id = this.id;
  63178. if (BABYLON.Tags) {
  63179. serializationObject.tags = BABYLON.Tags.GetTags(this);
  63180. }
  63181. serializationObject.materials = [];
  63182. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  63183. var subMat = this.subMaterials[matIndex];
  63184. if (subMat) {
  63185. serializationObject.materials.push(subMat.id);
  63186. }
  63187. else {
  63188. serializationObject.materials.push(null);
  63189. }
  63190. }
  63191. return serializationObject;
  63192. };
  63193. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  63194. var scene = this.getScene();
  63195. if (!scene) {
  63196. return;
  63197. }
  63198. var index = scene.multiMaterials.indexOf(this);
  63199. if (index >= 0) {
  63200. scene.multiMaterials.splice(index, 1);
  63201. }
  63202. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  63203. };
  63204. return MultiMaterial;
  63205. }(BABYLON.Material));
  63206. BABYLON.MultiMaterial = MultiMaterial;
  63207. })(BABYLON || (BABYLON = {}));
  63208. //# sourceMappingURL=babylon.multiMaterial.js.map
  63209. var BABYLON;
  63210. (function (BABYLON) {
  63211. var FreeCameraTouchInput = /** @class */ (function () {
  63212. function FreeCameraTouchInput() {
  63213. this._offsetX = null;
  63214. this._offsetY = null;
  63215. this._pointerPressed = new Array();
  63216. this.touchAngularSensibility = 200000.0;
  63217. this.touchMoveSensibility = 250.0;
  63218. }
  63219. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  63220. var _this = this;
  63221. var previousPosition = null;
  63222. if (this._pointerInput === undefined) {
  63223. this._onLostFocus = function (evt) {
  63224. _this._offsetX = null;
  63225. _this._offsetY = null;
  63226. };
  63227. this._pointerInput = function (p, s) {
  63228. var evt = p.event;
  63229. if (evt.pointerType === "mouse") {
  63230. return;
  63231. }
  63232. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  63233. if (!noPreventDefault) {
  63234. evt.preventDefault();
  63235. }
  63236. _this._pointerPressed.push(evt.pointerId);
  63237. if (_this._pointerPressed.length !== 1) {
  63238. return;
  63239. }
  63240. previousPosition = {
  63241. x: evt.clientX,
  63242. y: evt.clientY
  63243. };
  63244. }
  63245. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  63246. if (!noPreventDefault) {
  63247. evt.preventDefault();
  63248. }
  63249. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63250. if (index === -1) {
  63251. return;
  63252. }
  63253. _this._pointerPressed.splice(index, 1);
  63254. if (index != 0) {
  63255. return;
  63256. }
  63257. previousPosition = null;
  63258. _this._offsetX = null;
  63259. _this._offsetY = null;
  63260. }
  63261. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  63262. if (!noPreventDefault) {
  63263. evt.preventDefault();
  63264. }
  63265. if (!previousPosition) {
  63266. return;
  63267. }
  63268. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63269. if (index != 0) {
  63270. return;
  63271. }
  63272. _this._offsetX = evt.clientX - previousPosition.x;
  63273. _this._offsetY = -(evt.clientY - previousPosition.y);
  63274. }
  63275. };
  63276. }
  63277. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  63278. if (this._onLostFocus) {
  63279. element.addEventListener("blur", this._onLostFocus);
  63280. }
  63281. };
  63282. FreeCameraTouchInput.prototype.detachControl = function (element) {
  63283. if (this._pointerInput && element) {
  63284. if (this._observer) {
  63285. this.camera.getScene().onPointerObservable.remove(this._observer);
  63286. this._observer = null;
  63287. }
  63288. if (this._onLostFocus) {
  63289. element.removeEventListener("blur", this._onLostFocus);
  63290. this._onLostFocus = null;
  63291. }
  63292. this._pointerPressed = [];
  63293. this._offsetX = null;
  63294. this._offsetY = null;
  63295. }
  63296. };
  63297. FreeCameraTouchInput.prototype.checkInputs = function () {
  63298. if (this._offsetX && this._offsetY) {
  63299. var camera = this.camera;
  63300. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  63301. if (this._pointerPressed.length > 1) {
  63302. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  63303. }
  63304. else {
  63305. var speed = camera._computeLocalCameraSpeed();
  63306. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  63307. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  63308. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  63309. }
  63310. }
  63311. };
  63312. FreeCameraTouchInput.prototype.getClassName = function () {
  63313. return "FreeCameraTouchInput";
  63314. };
  63315. FreeCameraTouchInput.prototype.getSimpleName = function () {
  63316. return "touch";
  63317. };
  63318. __decorate([
  63319. BABYLON.serialize()
  63320. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  63321. __decorate([
  63322. BABYLON.serialize()
  63323. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  63324. return FreeCameraTouchInput;
  63325. }());
  63326. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  63327. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  63328. })(BABYLON || (BABYLON = {}));
  63329. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  63330. var BABYLON;
  63331. (function (BABYLON) {
  63332. // We're mainly based on the logic defined into the FreeCamera code
  63333. var TouchCamera = /** @class */ (function (_super) {
  63334. __extends(TouchCamera, _super);
  63335. //-- end properties for backward compatibility for inputs
  63336. function TouchCamera(name, position, scene) {
  63337. var _this = _super.call(this, name, position, scene) || this;
  63338. _this.inputs.addTouch();
  63339. _this._setupInputs();
  63340. return _this;
  63341. }
  63342. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  63343. //-- Begin properties for backward compatibility for inputs
  63344. get: function () {
  63345. var touch = this.inputs.attached["touch"];
  63346. if (touch)
  63347. return touch.touchAngularSensibility;
  63348. return 0;
  63349. },
  63350. set: function (value) {
  63351. var touch = this.inputs.attached["touch"];
  63352. if (touch)
  63353. touch.touchAngularSensibility = value;
  63354. },
  63355. enumerable: true,
  63356. configurable: true
  63357. });
  63358. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  63359. get: function () {
  63360. var touch = this.inputs.attached["touch"];
  63361. if (touch)
  63362. return touch.touchMoveSensibility;
  63363. return 0;
  63364. },
  63365. set: function (value) {
  63366. var touch = this.inputs.attached["touch"];
  63367. if (touch)
  63368. touch.touchMoveSensibility = value;
  63369. },
  63370. enumerable: true,
  63371. configurable: true
  63372. });
  63373. TouchCamera.prototype.getClassName = function () {
  63374. return "TouchCamera";
  63375. };
  63376. TouchCamera.prototype._setupInputs = function () {
  63377. var mouse = this.inputs.attached["mouse"];
  63378. if (mouse) {
  63379. mouse.touchEnabled = false;
  63380. }
  63381. };
  63382. return TouchCamera;
  63383. }(BABYLON.FreeCamera));
  63384. BABYLON.TouchCamera = TouchCamera;
  63385. })(BABYLON || (BABYLON = {}));
  63386. //# sourceMappingURL=babylon.touchCamera.js.map
  63387. var BABYLON;
  63388. (function (BABYLON) {
  63389. var ProceduralTexture = /** @class */ (function (_super) {
  63390. __extends(ProceduralTexture, _super);
  63391. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  63392. if (fallbackTexture === void 0) { fallbackTexture = null; }
  63393. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63394. if (isCube === void 0) { isCube = false; }
  63395. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63396. _this.isCube = isCube;
  63397. _this.isEnabled = true;
  63398. _this._currentRefreshId = -1;
  63399. _this._refreshRate = 1;
  63400. _this._vertexBuffers = {};
  63401. _this._uniforms = new Array();
  63402. _this._samplers = new Array();
  63403. _this._textures = {};
  63404. _this._floats = {};
  63405. _this._floatsArrays = {};
  63406. _this._colors3 = {};
  63407. _this._colors4 = {};
  63408. _this._vectors2 = {};
  63409. _this._vectors3 = {};
  63410. _this._matrices = {};
  63411. _this._fallbackTextureUsed = false;
  63412. scene._proceduralTextures.push(_this);
  63413. _this._engine = scene.getEngine();
  63414. _this.name = name;
  63415. _this.isRenderTarget = true;
  63416. _this._size = size;
  63417. _this._generateMipMaps = generateMipMaps;
  63418. _this.setFragment(fragment);
  63419. _this._fallbackTexture = fallbackTexture;
  63420. if (isCube) {
  63421. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  63422. _this.setFloat("face", 0);
  63423. }
  63424. else {
  63425. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  63426. }
  63427. // VBO
  63428. var vertices = [];
  63429. vertices.push(1, 1);
  63430. vertices.push(-1, 1);
  63431. vertices.push(-1, -1);
  63432. vertices.push(1, -1);
  63433. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63434. _this._createIndexBuffer();
  63435. return _this;
  63436. }
  63437. ProceduralTexture.prototype._createIndexBuffer = function () {
  63438. var engine = this._engine;
  63439. // Indices
  63440. var indices = [];
  63441. indices.push(0);
  63442. indices.push(1);
  63443. indices.push(2);
  63444. indices.push(0);
  63445. indices.push(2);
  63446. indices.push(3);
  63447. this._indexBuffer = engine.createIndexBuffer(indices);
  63448. };
  63449. ProceduralTexture.prototype._rebuild = function () {
  63450. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63451. if (vb) {
  63452. vb._rebuild();
  63453. }
  63454. this._createIndexBuffer();
  63455. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63456. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63457. }
  63458. };
  63459. ProceduralTexture.prototype.reset = function () {
  63460. if (this._effect === undefined) {
  63461. return;
  63462. }
  63463. var engine = this._engine;
  63464. engine._releaseEffect(this._effect);
  63465. };
  63466. ProceduralTexture.prototype.isReady = function () {
  63467. var _this = this;
  63468. var engine = this._engine;
  63469. var shaders;
  63470. if (!this._fragment) {
  63471. return false;
  63472. }
  63473. if (this._fallbackTextureUsed) {
  63474. return true;
  63475. }
  63476. if (this._fragment.fragmentElement !== undefined) {
  63477. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  63478. }
  63479. else {
  63480. shaders = { vertex: "procedural", fragment: this._fragment };
  63481. }
  63482. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  63483. _this.releaseInternalTexture();
  63484. if (_this._fallbackTexture) {
  63485. _this._texture = _this._fallbackTexture._texture;
  63486. if (_this._texture) {
  63487. _this._texture.incrementReferences();
  63488. }
  63489. }
  63490. _this._fallbackTextureUsed = true;
  63491. });
  63492. return this._effect.isReady();
  63493. };
  63494. ProceduralTexture.prototype.resetRefreshCounter = function () {
  63495. this._currentRefreshId = -1;
  63496. };
  63497. ProceduralTexture.prototype.setFragment = function (fragment) {
  63498. this._fragment = fragment;
  63499. };
  63500. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  63501. get: function () {
  63502. return this._refreshRate;
  63503. },
  63504. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63505. set: function (value) {
  63506. this._refreshRate = value;
  63507. this.resetRefreshCounter();
  63508. },
  63509. enumerable: true,
  63510. configurable: true
  63511. });
  63512. ProceduralTexture.prototype._shouldRender = function () {
  63513. if (!this.isEnabled || !this.isReady() || !this._texture) {
  63514. return false;
  63515. }
  63516. if (this._fallbackTextureUsed) {
  63517. return false;
  63518. }
  63519. if (this._currentRefreshId === -1) {
  63520. this._currentRefreshId = 1;
  63521. return true;
  63522. }
  63523. if (this.refreshRate === this._currentRefreshId) {
  63524. this._currentRefreshId = 1;
  63525. return true;
  63526. }
  63527. this._currentRefreshId++;
  63528. return false;
  63529. };
  63530. ProceduralTexture.prototype.getRenderSize = function () {
  63531. return this._size;
  63532. };
  63533. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  63534. if (this._fallbackTextureUsed) {
  63535. return;
  63536. }
  63537. this.releaseInternalTexture();
  63538. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  63539. };
  63540. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  63541. if (this._uniforms.indexOf(uniformName) === -1) {
  63542. this._uniforms.push(uniformName);
  63543. }
  63544. };
  63545. ProceduralTexture.prototype.setTexture = function (name, texture) {
  63546. if (this._samplers.indexOf(name) === -1) {
  63547. this._samplers.push(name);
  63548. }
  63549. this._textures[name] = texture;
  63550. return this;
  63551. };
  63552. ProceduralTexture.prototype.setFloat = function (name, value) {
  63553. this._checkUniform(name);
  63554. this._floats[name] = value;
  63555. return this;
  63556. };
  63557. ProceduralTexture.prototype.setFloats = function (name, value) {
  63558. this._checkUniform(name);
  63559. this._floatsArrays[name] = value;
  63560. return this;
  63561. };
  63562. ProceduralTexture.prototype.setColor3 = function (name, value) {
  63563. this._checkUniform(name);
  63564. this._colors3[name] = value;
  63565. return this;
  63566. };
  63567. ProceduralTexture.prototype.setColor4 = function (name, value) {
  63568. this._checkUniform(name);
  63569. this._colors4[name] = value;
  63570. return this;
  63571. };
  63572. ProceduralTexture.prototype.setVector2 = function (name, value) {
  63573. this._checkUniform(name);
  63574. this._vectors2[name] = value;
  63575. return this;
  63576. };
  63577. ProceduralTexture.prototype.setVector3 = function (name, value) {
  63578. this._checkUniform(name);
  63579. this._vectors3[name] = value;
  63580. return this;
  63581. };
  63582. ProceduralTexture.prototype.setMatrix = function (name, value) {
  63583. this._checkUniform(name);
  63584. this._matrices[name] = value;
  63585. return this;
  63586. };
  63587. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63588. var scene = this.getScene();
  63589. if (!scene) {
  63590. return;
  63591. }
  63592. var engine = this._engine;
  63593. // Render
  63594. engine.enableEffect(this._effect);
  63595. engine.setState(false);
  63596. // Texture
  63597. for (var name in this._textures) {
  63598. this._effect.setTexture(name, this._textures[name]);
  63599. }
  63600. // Float
  63601. for (name in this._floats) {
  63602. this._effect.setFloat(name, this._floats[name]);
  63603. }
  63604. // Floats
  63605. for (name in this._floatsArrays) {
  63606. this._effect.setArray(name, this._floatsArrays[name]);
  63607. }
  63608. // Color3
  63609. for (name in this._colors3) {
  63610. this._effect.setColor3(name, this._colors3[name]);
  63611. }
  63612. // Color4
  63613. for (name in this._colors4) {
  63614. var color = this._colors4[name];
  63615. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  63616. }
  63617. // Vector2
  63618. for (name in this._vectors2) {
  63619. this._effect.setVector2(name, this._vectors2[name]);
  63620. }
  63621. // Vector3
  63622. for (name in this._vectors3) {
  63623. this._effect.setVector3(name, this._vectors3[name]);
  63624. }
  63625. // Matrix
  63626. for (name in this._matrices) {
  63627. this._effect.setMatrix(name, this._matrices[name]);
  63628. }
  63629. if (!this._texture) {
  63630. return;
  63631. }
  63632. if (this.isCube) {
  63633. for (var face = 0; face < 6; face++) {
  63634. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  63635. // VBOs
  63636. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63637. this._effect.setFloat("face", face);
  63638. // Clear
  63639. engine.clear(scene.clearColor, true, true, true);
  63640. // Draw order
  63641. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63642. // Mipmaps
  63643. if (face === 5) {
  63644. engine.generateMipMapsForCubemap(this._texture);
  63645. }
  63646. }
  63647. }
  63648. else {
  63649. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  63650. // VBOs
  63651. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63652. // Clear
  63653. engine.clear(scene.clearColor, true, true, true);
  63654. // Draw order
  63655. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63656. }
  63657. // Unbind
  63658. engine.unBindFramebuffer(this._texture, this.isCube);
  63659. if (this.onGenerated) {
  63660. this.onGenerated();
  63661. }
  63662. };
  63663. ProceduralTexture.prototype.clone = function () {
  63664. var textureSize = this.getSize();
  63665. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  63666. // Base texture
  63667. newTexture.hasAlpha = this.hasAlpha;
  63668. newTexture.level = this.level;
  63669. // RenderTarget Texture
  63670. newTexture.coordinatesMode = this.coordinatesMode;
  63671. return newTexture;
  63672. };
  63673. ProceduralTexture.prototype.dispose = function () {
  63674. var scene = this.getScene();
  63675. if (!scene) {
  63676. return;
  63677. }
  63678. var index = scene._proceduralTextures.indexOf(this);
  63679. if (index >= 0) {
  63680. scene._proceduralTextures.splice(index, 1);
  63681. }
  63682. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63683. if (vertexBuffer) {
  63684. vertexBuffer.dispose();
  63685. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63686. }
  63687. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  63688. this._indexBuffer = null;
  63689. }
  63690. _super.prototype.dispose.call(this);
  63691. };
  63692. return ProceduralTexture;
  63693. }(BABYLON.Texture));
  63694. BABYLON.ProceduralTexture = ProceduralTexture;
  63695. })(BABYLON || (BABYLON = {}));
  63696. //# sourceMappingURL=babylon.proceduralTexture.js.map
  63697. var BABYLON;
  63698. (function (BABYLON) {
  63699. var CustomProceduralTexture = /** @class */ (function (_super) {
  63700. __extends(CustomProceduralTexture, _super);
  63701. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  63702. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  63703. _this._animate = true;
  63704. _this._time = 0;
  63705. _this._texturePath = texturePath;
  63706. //Try to load json
  63707. _this.loadJson(texturePath);
  63708. _this.refreshRate = 1;
  63709. return _this;
  63710. }
  63711. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  63712. var _this = this;
  63713. var noConfigFile = function () {
  63714. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  63715. try {
  63716. _this.setFragment(_this._texturePath);
  63717. }
  63718. catch (ex) {
  63719. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  63720. }
  63721. };
  63722. var configFileUrl = jsonUrl + "/config.json";
  63723. var xhr = new XMLHttpRequest();
  63724. xhr.open("GET", configFileUrl, true);
  63725. xhr.addEventListener("load", function () {
  63726. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63727. try {
  63728. _this._config = JSON.parse(xhr.response);
  63729. _this.updateShaderUniforms();
  63730. _this.updateTextures();
  63731. _this.setFragment(_this._texturePath + "/custom");
  63732. _this._animate = _this._config.animate;
  63733. _this.refreshRate = _this._config.refreshrate;
  63734. }
  63735. catch (ex) {
  63736. noConfigFile();
  63737. }
  63738. }
  63739. else {
  63740. noConfigFile();
  63741. }
  63742. }, false);
  63743. xhr.addEventListener("error", function () {
  63744. noConfigFile();
  63745. }, false);
  63746. try {
  63747. xhr.send();
  63748. }
  63749. catch (ex) {
  63750. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  63751. }
  63752. };
  63753. CustomProceduralTexture.prototype.isReady = function () {
  63754. if (!_super.prototype.isReady.call(this)) {
  63755. return false;
  63756. }
  63757. for (var name in this._textures) {
  63758. var texture = this._textures[name];
  63759. if (!texture.isReady()) {
  63760. return false;
  63761. }
  63762. }
  63763. return true;
  63764. };
  63765. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63766. var scene = this.getScene();
  63767. if (this._animate && scene) {
  63768. this._time += scene.getAnimationRatio() * 0.03;
  63769. this.updateShaderUniforms();
  63770. }
  63771. _super.prototype.render.call(this, useCameraPostProcess);
  63772. };
  63773. CustomProceduralTexture.prototype.updateTextures = function () {
  63774. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  63775. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  63776. }
  63777. };
  63778. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  63779. if (this._config) {
  63780. for (var j = 0; j < this._config.uniforms.length; j++) {
  63781. var uniform = this._config.uniforms[j];
  63782. switch (uniform.type) {
  63783. case "float":
  63784. this.setFloat(uniform.name, uniform.value);
  63785. break;
  63786. case "color3":
  63787. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  63788. break;
  63789. case "color4":
  63790. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  63791. break;
  63792. case "vector2":
  63793. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  63794. break;
  63795. case "vector3":
  63796. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  63797. break;
  63798. }
  63799. }
  63800. }
  63801. this.setFloat("time", this._time);
  63802. };
  63803. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  63804. get: function () {
  63805. return this._animate;
  63806. },
  63807. set: function (value) {
  63808. this._animate = value;
  63809. },
  63810. enumerable: true,
  63811. configurable: true
  63812. });
  63813. return CustomProceduralTexture;
  63814. }(BABYLON.ProceduralTexture));
  63815. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  63816. })(BABYLON || (BABYLON = {}));
  63817. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  63818. var BABYLON;
  63819. (function (BABYLON) {
  63820. var FreeCameraGamepadInput = /** @class */ (function () {
  63821. function FreeCameraGamepadInput() {
  63822. this.gamepadAngularSensibility = 200;
  63823. this.gamepadMoveSensibility = 40;
  63824. // private members
  63825. this._cameraTransform = BABYLON.Matrix.Identity();
  63826. this._deltaTransform = BABYLON.Vector3.Zero();
  63827. this._vector3 = BABYLON.Vector3.Zero();
  63828. this._vector2 = BABYLON.Vector2.Zero();
  63829. }
  63830. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63831. var _this = this;
  63832. var manager = this.camera.getScene().gamepadManager;
  63833. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63834. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63835. // prioritize XBOX gamepads.
  63836. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63837. _this.gamepad = gamepad;
  63838. }
  63839. }
  63840. });
  63841. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63842. if (_this.gamepad === gamepad) {
  63843. _this.gamepad = null;
  63844. }
  63845. });
  63846. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63847. };
  63848. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  63849. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63850. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63851. this.gamepad = null;
  63852. };
  63853. FreeCameraGamepadInput.prototype.checkInputs = function () {
  63854. if (this.gamepad && this.gamepad.leftStick) {
  63855. var camera = this.camera;
  63856. var LSValues = this.gamepad.leftStick;
  63857. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  63858. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63859. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  63860. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  63861. var RSValues = this.gamepad.rightStick;
  63862. if (RSValues) {
  63863. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  63864. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  63865. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  63866. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  63867. }
  63868. else {
  63869. RSValues = { x: 0, y: 0 };
  63870. }
  63871. if (!camera.rotationQuaternion) {
  63872. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  63873. }
  63874. else {
  63875. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  63876. }
  63877. var speed = camera._computeLocalCameraSpeed() * 50.0;
  63878. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  63879. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  63880. camera.cameraDirection.addInPlace(this._deltaTransform);
  63881. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  63882. camera.cameraRotation.addInPlace(this._vector2);
  63883. }
  63884. };
  63885. FreeCameraGamepadInput.prototype.getClassName = function () {
  63886. return "FreeCameraGamepadInput";
  63887. };
  63888. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  63889. return "gamepad";
  63890. };
  63891. __decorate([
  63892. BABYLON.serialize()
  63893. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  63894. __decorate([
  63895. BABYLON.serialize()
  63896. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63897. return FreeCameraGamepadInput;
  63898. }());
  63899. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  63900. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  63901. })(BABYLON || (BABYLON = {}));
  63902. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  63903. var BABYLON;
  63904. (function (BABYLON) {
  63905. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  63906. function ArcRotateCameraGamepadInput() {
  63907. this.gamepadRotationSensibility = 80;
  63908. this.gamepadMoveSensibility = 40;
  63909. }
  63910. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63911. var _this = this;
  63912. var manager = this.camera.getScene().gamepadManager;
  63913. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63914. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63915. // prioritize XBOX gamepads.
  63916. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63917. _this.gamepad = gamepad;
  63918. }
  63919. }
  63920. });
  63921. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63922. if (_this.gamepad === gamepad) {
  63923. _this.gamepad = null;
  63924. }
  63925. });
  63926. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63927. };
  63928. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  63929. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63930. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63931. this.gamepad = null;
  63932. };
  63933. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  63934. if (this.gamepad) {
  63935. var camera = this.camera;
  63936. var RSValues = this.gamepad.rightStick;
  63937. if (RSValues) {
  63938. if (RSValues.x != 0) {
  63939. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  63940. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  63941. camera.inertialAlphaOffset += normalizedRX;
  63942. }
  63943. }
  63944. if (RSValues.y != 0) {
  63945. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  63946. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  63947. camera.inertialBetaOffset += normalizedRY;
  63948. }
  63949. }
  63950. }
  63951. var LSValues = this.gamepad.leftStick;
  63952. if (LSValues && LSValues.y != 0) {
  63953. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63954. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  63955. this.camera.inertialRadiusOffset -= normalizedLY;
  63956. }
  63957. }
  63958. }
  63959. };
  63960. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  63961. return "ArcRotateCameraGamepadInput";
  63962. };
  63963. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  63964. return "gamepad";
  63965. };
  63966. __decorate([
  63967. BABYLON.serialize()
  63968. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  63969. __decorate([
  63970. BABYLON.serialize()
  63971. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63972. return ArcRotateCameraGamepadInput;
  63973. }());
  63974. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  63975. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  63976. })(BABYLON || (BABYLON = {}));
  63977. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  63978. var BABYLON;
  63979. (function (BABYLON) {
  63980. var GamepadManager = /** @class */ (function () {
  63981. function GamepadManager(_scene) {
  63982. var _this = this;
  63983. this._scene = _scene;
  63984. this._babylonGamepads = [];
  63985. this._oneGamepadConnected = false;
  63986. this._isMonitoring = false;
  63987. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  63988. if (!BABYLON.Tools.IsWindowObjectExist()) {
  63989. this._gamepadEventSupported = false;
  63990. }
  63991. else {
  63992. this._gamepadEventSupported = 'GamepadEvent' in window;
  63993. this._gamepadSupport = (navigator.getGamepads ||
  63994. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  63995. }
  63996. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  63997. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  63998. for (var i in _this._babylonGamepads) {
  63999. var gamepad = _this._babylonGamepads[i];
  64000. if (gamepad && gamepad._isConnected) {
  64001. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  64002. }
  64003. }
  64004. });
  64005. this._onGamepadConnectedEvent = function (evt) {
  64006. var gamepad = evt.gamepad;
  64007. if (gamepad.index in _this._babylonGamepads) {
  64008. if (_this._babylonGamepads[gamepad.index].isConnected) {
  64009. return;
  64010. }
  64011. }
  64012. var newGamepad;
  64013. if (_this._babylonGamepads[gamepad.index]) {
  64014. newGamepad = _this._babylonGamepads[gamepad.index];
  64015. newGamepad.browserGamepad = gamepad;
  64016. newGamepad._isConnected = true;
  64017. }
  64018. else {
  64019. newGamepad = _this._addNewGamepad(gamepad);
  64020. }
  64021. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64022. _this._startMonitoringGamepads();
  64023. };
  64024. this._onGamepadDisconnectedEvent = function (evt) {
  64025. var gamepad = evt.gamepad;
  64026. // Remove the gamepad from the list of gamepads to monitor.
  64027. for (var i in _this._babylonGamepads) {
  64028. if (_this._babylonGamepads[i].index === gamepad.index) {
  64029. var disconnectedGamepad = _this._babylonGamepads[i];
  64030. disconnectedGamepad._isConnected = false;
  64031. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  64032. break;
  64033. }
  64034. }
  64035. };
  64036. if (this._gamepadSupport) {
  64037. //first add already-connected gamepads
  64038. this._updateGamepadObjects();
  64039. if (this._babylonGamepads.length) {
  64040. this._startMonitoringGamepads();
  64041. }
  64042. // Checking if the gamepad connected event is supported (like in Firefox)
  64043. if (this._gamepadEventSupported) {
  64044. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  64045. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  64046. }
  64047. else {
  64048. this._startMonitoringGamepads();
  64049. }
  64050. }
  64051. }
  64052. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  64053. get: function () {
  64054. return this._babylonGamepads;
  64055. },
  64056. enumerable: true,
  64057. configurable: true
  64058. });
  64059. GamepadManager.prototype.getGamepadByType = function (type) {
  64060. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  64061. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  64062. var gamepad = _a[_i];
  64063. if (gamepad && gamepad.type === type) {
  64064. return gamepad;
  64065. }
  64066. }
  64067. return null;
  64068. };
  64069. GamepadManager.prototype.dispose = function () {
  64070. if (this._gamepadEventSupported) {
  64071. if (this._onGamepadConnectedEvent) {
  64072. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  64073. }
  64074. if (this._onGamepadDisconnectedEvent) {
  64075. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  64076. }
  64077. this._onGamepadConnectedEvent = null;
  64078. this._onGamepadDisconnectedEvent = null;
  64079. }
  64080. this._babylonGamepads.forEach(function (gamepad) {
  64081. gamepad.dispose();
  64082. });
  64083. this.onGamepadConnectedObservable.clear();
  64084. this.onGamepadDisconnectedObservable.clear();
  64085. this._oneGamepadConnected = false;
  64086. this._stopMonitoringGamepads();
  64087. this._babylonGamepads = [];
  64088. };
  64089. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  64090. if (!this._oneGamepadConnected) {
  64091. this._oneGamepadConnected = true;
  64092. }
  64093. var newGamepad;
  64094. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  64095. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  64096. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  64097. }
  64098. else if (gamepad.pose) {
  64099. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  64100. }
  64101. else {
  64102. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  64103. }
  64104. this._babylonGamepads[newGamepad.index] = newGamepad;
  64105. return newGamepad;
  64106. };
  64107. GamepadManager.prototype._startMonitoringGamepads = function () {
  64108. if (!this._isMonitoring) {
  64109. this._isMonitoring = true;
  64110. //back-comp
  64111. if (!this._scene) {
  64112. this._checkGamepadsStatus();
  64113. }
  64114. }
  64115. };
  64116. GamepadManager.prototype._stopMonitoringGamepads = function () {
  64117. this._isMonitoring = false;
  64118. };
  64119. GamepadManager.prototype._checkGamepadsStatus = function () {
  64120. var _this = this;
  64121. // Hack to be compatible Chrome
  64122. this._updateGamepadObjects();
  64123. for (var i in this._babylonGamepads) {
  64124. var gamepad = this._babylonGamepads[i];
  64125. if (!gamepad || !gamepad.isConnected) {
  64126. continue;
  64127. }
  64128. gamepad.update();
  64129. }
  64130. if (this._isMonitoring && !this._scene) {
  64131. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  64132. }
  64133. };
  64134. // This function is called only on Chrome, which does not properly support
  64135. // connection/disconnection events and forces you to recopy again the gamepad object
  64136. GamepadManager.prototype._updateGamepadObjects = function () {
  64137. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  64138. for (var i = 0; i < gamepads.length; i++) {
  64139. if (gamepads[i]) {
  64140. if (!this._babylonGamepads[gamepads[i].index]) {
  64141. var newGamepad = this._addNewGamepad(gamepads[i]);
  64142. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64143. }
  64144. else {
  64145. // Forced to copy again this object for Chrome for unknown reason
  64146. this._babylonGamepads[i].browserGamepad = gamepads[i];
  64147. if (!this._babylonGamepads[i].isConnected) {
  64148. this._babylonGamepads[i]._isConnected = true;
  64149. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  64150. }
  64151. }
  64152. }
  64153. }
  64154. };
  64155. return GamepadManager;
  64156. }());
  64157. BABYLON.GamepadManager = GamepadManager;
  64158. })(BABYLON || (BABYLON = {}));
  64159. //# sourceMappingURL=babylon.gamepadManager.js.map
  64160. var BABYLON;
  64161. (function (BABYLON) {
  64162. var StickValues = /** @class */ (function () {
  64163. function StickValues(x, y) {
  64164. this.x = x;
  64165. this.y = y;
  64166. }
  64167. return StickValues;
  64168. }());
  64169. BABYLON.StickValues = StickValues;
  64170. var Gamepad = /** @class */ (function () {
  64171. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  64172. if (leftStickX === void 0) { leftStickX = 0; }
  64173. if (leftStickY === void 0) { leftStickY = 1; }
  64174. if (rightStickX === void 0) { rightStickX = 2; }
  64175. if (rightStickY === void 0) { rightStickY = 3; }
  64176. this.id = id;
  64177. this.index = index;
  64178. this.browserGamepad = browserGamepad;
  64179. this._isConnected = true;
  64180. this._invertLeftStickY = false;
  64181. this.type = Gamepad.GAMEPAD;
  64182. this._leftStickAxisX = leftStickX;
  64183. this._leftStickAxisY = leftStickY;
  64184. this._rightStickAxisX = rightStickX;
  64185. this._rightStickAxisY = rightStickY;
  64186. if (this.browserGamepad.axes.length >= 2) {
  64187. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64188. }
  64189. if (this.browserGamepad.axes.length >= 4) {
  64190. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64191. }
  64192. }
  64193. Object.defineProperty(Gamepad.prototype, "isConnected", {
  64194. get: function () {
  64195. return this._isConnected;
  64196. },
  64197. enumerable: true,
  64198. configurable: true
  64199. });
  64200. Gamepad.prototype.onleftstickchanged = function (callback) {
  64201. this._onleftstickchanged = callback;
  64202. };
  64203. Gamepad.prototype.onrightstickchanged = function (callback) {
  64204. this._onrightstickchanged = callback;
  64205. };
  64206. Object.defineProperty(Gamepad.prototype, "leftStick", {
  64207. get: function () {
  64208. return this._leftStick;
  64209. },
  64210. set: function (newValues) {
  64211. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  64212. this._onleftstickchanged(newValues);
  64213. }
  64214. this._leftStick = newValues;
  64215. },
  64216. enumerable: true,
  64217. configurable: true
  64218. });
  64219. Object.defineProperty(Gamepad.prototype, "rightStick", {
  64220. get: function () {
  64221. return this._rightStick;
  64222. },
  64223. set: function (newValues) {
  64224. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  64225. this._onrightstickchanged(newValues);
  64226. }
  64227. this._rightStick = newValues;
  64228. },
  64229. enumerable: true,
  64230. configurable: true
  64231. });
  64232. Gamepad.prototype.update = function () {
  64233. if (this._leftStick) {
  64234. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64235. if (this._invertLeftStickY) {
  64236. this.leftStick.y *= -1;
  64237. }
  64238. }
  64239. if (this._rightStick) {
  64240. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64241. }
  64242. };
  64243. Gamepad.prototype.dispose = function () {
  64244. };
  64245. Gamepad.GAMEPAD = 0;
  64246. Gamepad.GENERIC = 1;
  64247. Gamepad.XBOX = 2;
  64248. Gamepad.POSE_ENABLED = 3;
  64249. return Gamepad;
  64250. }());
  64251. BABYLON.Gamepad = Gamepad;
  64252. var GenericPad = /** @class */ (function (_super) {
  64253. __extends(GenericPad, _super);
  64254. function GenericPad(id, index, browserGamepad) {
  64255. var _this = _super.call(this, id, index, browserGamepad) || this;
  64256. _this.onButtonDownObservable = new BABYLON.Observable();
  64257. _this.onButtonUpObservable = new BABYLON.Observable();
  64258. _this.type = Gamepad.GENERIC;
  64259. _this._buttons = new Array(browserGamepad.buttons.length);
  64260. return _this;
  64261. }
  64262. GenericPad.prototype.onbuttondown = function (callback) {
  64263. this._onbuttondown = callback;
  64264. };
  64265. GenericPad.prototype.onbuttonup = function (callback) {
  64266. this._onbuttonup = callback;
  64267. };
  64268. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  64269. if (newValue !== currentValue) {
  64270. if (newValue === 1) {
  64271. if (this._onbuttondown) {
  64272. this._onbuttondown(buttonIndex);
  64273. }
  64274. this.onButtonDownObservable.notifyObservers(buttonIndex);
  64275. }
  64276. if (newValue === 0) {
  64277. if (this._onbuttonup) {
  64278. this._onbuttonup(buttonIndex);
  64279. }
  64280. this.onButtonUpObservable.notifyObservers(buttonIndex);
  64281. }
  64282. }
  64283. return newValue;
  64284. };
  64285. GenericPad.prototype.update = function () {
  64286. _super.prototype.update.call(this);
  64287. for (var index = 0; index < this._buttons.length; index++) {
  64288. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  64289. }
  64290. };
  64291. GenericPad.prototype.dispose = function () {
  64292. _super.prototype.dispose.call(this);
  64293. this.onButtonDownObservable.clear();
  64294. this.onButtonUpObservable.clear();
  64295. };
  64296. return GenericPad;
  64297. }(Gamepad));
  64298. BABYLON.GenericPad = GenericPad;
  64299. })(BABYLON || (BABYLON = {}));
  64300. //# sourceMappingURL=babylon.gamepad.js.map
  64301. var BABYLON;
  64302. (function (BABYLON) {
  64303. var Xbox360Button;
  64304. (function (Xbox360Button) {
  64305. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  64306. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  64307. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  64308. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  64309. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  64310. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  64311. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  64312. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  64313. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  64314. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  64315. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  64316. var Xbox360Dpad;
  64317. (function (Xbox360Dpad) {
  64318. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  64319. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  64320. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  64321. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  64322. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  64323. var Xbox360Pad = /** @class */ (function (_super) {
  64324. __extends(Xbox360Pad, _super);
  64325. function Xbox360Pad(id, index, gamepad, xboxOne) {
  64326. if (xboxOne === void 0) { xboxOne = false; }
  64327. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  64328. _this._leftTrigger = 0;
  64329. _this._rightTrigger = 0;
  64330. _this.onButtonDownObservable = new BABYLON.Observable();
  64331. _this.onButtonUpObservable = new BABYLON.Observable();
  64332. _this.onPadDownObservable = new BABYLON.Observable();
  64333. _this.onPadUpObservable = new BABYLON.Observable();
  64334. _this._buttonA = 0;
  64335. _this._buttonB = 0;
  64336. _this._buttonX = 0;
  64337. _this._buttonY = 0;
  64338. _this._buttonBack = 0;
  64339. _this._buttonStart = 0;
  64340. _this._buttonLB = 0;
  64341. _this._buttonRB = 0;
  64342. _this._buttonLeftStick = 0;
  64343. _this._buttonRightStick = 0;
  64344. _this._dPadUp = 0;
  64345. _this._dPadDown = 0;
  64346. _this._dPadLeft = 0;
  64347. _this._dPadRight = 0;
  64348. _this._isXboxOnePad = false;
  64349. _this.type = BABYLON.Gamepad.XBOX;
  64350. _this._isXboxOnePad = xboxOne;
  64351. return _this;
  64352. }
  64353. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  64354. this._onlefttriggerchanged = callback;
  64355. };
  64356. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  64357. this._onrighttriggerchanged = callback;
  64358. };
  64359. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  64360. get: function () {
  64361. return this._leftTrigger;
  64362. },
  64363. set: function (newValue) {
  64364. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  64365. this._onlefttriggerchanged(newValue);
  64366. }
  64367. this._leftTrigger = newValue;
  64368. },
  64369. enumerable: true,
  64370. configurable: true
  64371. });
  64372. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  64373. get: function () {
  64374. return this._rightTrigger;
  64375. },
  64376. set: function (newValue) {
  64377. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  64378. this._onrighttriggerchanged(newValue);
  64379. }
  64380. this._rightTrigger = newValue;
  64381. },
  64382. enumerable: true,
  64383. configurable: true
  64384. });
  64385. Xbox360Pad.prototype.onbuttondown = function (callback) {
  64386. this._onbuttondown = callback;
  64387. };
  64388. Xbox360Pad.prototype.onbuttonup = function (callback) {
  64389. this._onbuttonup = callback;
  64390. };
  64391. Xbox360Pad.prototype.ondpaddown = function (callback) {
  64392. this._ondpaddown = callback;
  64393. };
  64394. Xbox360Pad.prototype.ondpadup = function (callback) {
  64395. this._ondpadup = callback;
  64396. };
  64397. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  64398. if (newValue !== currentValue) {
  64399. if (newValue === 1) {
  64400. if (this._onbuttondown) {
  64401. this._onbuttondown(buttonType);
  64402. }
  64403. this.onButtonDownObservable.notifyObservers(buttonType);
  64404. }
  64405. if (newValue === 0) {
  64406. if (this._onbuttonup) {
  64407. this._onbuttonup(buttonType);
  64408. }
  64409. this.onButtonUpObservable.notifyObservers(buttonType);
  64410. }
  64411. }
  64412. return newValue;
  64413. };
  64414. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  64415. if (newValue !== currentValue) {
  64416. if (newValue === 1) {
  64417. if (this._ondpaddown) {
  64418. this._ondpaddown(buttonType);
  64419. }
  64420. this.onPadDownObservable.notifyObservers(buttonType);
  64421. }
  64422. if (newValue === 0) {
  64423. if (this._ondpadup) {
  64424. this._ondpadup(buttonType);
  64425. }
  64426. this.onPadUpObservable.notifyObservers(buttonType);
  64427. }
  64428. }
  64429. return newValue;
  64430. };
  64431. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  64432. get: function () {
  64433. return this._buttonA;
  64434. },
  64435. set: function (value) {
  64436. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  64437. },
  64438. enumerable: true,
  64439. configurable: true
  64440. });
  64441. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  64442. get: function () {
  64443. return this._buttonB;
  64444. },
  64445. set: function (value) {
  64446. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  64447. },
  64448. enumerable: true,
  64449. configurable: true
  64450. });
  64451. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  64452. get: function () {
  64453. return this._buttonX;
  64454. },
  64455. set: function (value) {
  64456. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  64457. },
  64458. enumerable: true,
  64459. configurable: true
  64460. });
  64461. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  64462. get: function () {
  64463. return this._buttonY;
  64464. },
  64465. set: function (value) {
  64466. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  64467. },
  64468. enumerable: true,
  64469. configurable: true
  64470. });
  64471. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  64472. get: function () {
  64473. return this._buttonStart;
  64474. },
  64475. set: function (value) {
  64476. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  64477. },
  64478. enumerable: true,
  64479. configurable: true
  64480. });
  64481. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  64482. get: function () {
  64483. return this._buttonBack;
  64484. },
  64485. set: function (value) {
  64486. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  64487. },
  64488. enumerable: true,
  64489. configurable: true
  64490. });
  64491. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  64492. get: function () {
  64493. return this._buttonLB;
  64494. },
  64495. set: function (value) {
  64496. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  64497. },
  64498. enumerable: true,
  64499. configurable: true
  64500. });
  64501. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  64502. get: function () {
  64503. return this._buttonRB;
  64504. },
  64505. set: function (value) {
  64506. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  64507. },
  64508. enumerable: true,
  64509. configurable: true
  64510. });
  64511. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  64512. get: function () {
  64513. return this._buttonLeftStick;
  64514. },
  64515. set: function (value) {
  64516. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  64517. },
  64518. enumerable: true,
  64519. configurable: true
  64520. });
  64521. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  64522. get: function () {
  64523. return this._buttonRightStick;
  64524. },
  64525. set: function (value) {
  64526. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  64527. },
  64528. enumerable: true,
  64529. configurable: true
  64530. });
  64531. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  64532. get: function () {
  64533. return this._dPadUp;
  64534. },
  64535. set: function (value) {
  64536. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  64537. },
  64538. enumerable: true,
  64539. configurable: true
  64540. });
  64541. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  64542. get: function () {
  64543. return this._dPadDown;
  64544. },
  64545. set: function (value) {
  64546. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  64547. },
  64548. enumerable: true,
  64549. configurable: true
  64550. });
  64551. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  64552. get: function () {
  64553. return this._dPadLeft;
  64554. },
  64555. set: function (value) {
  64556. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  64557. },
  64558. enumerable: true,
  64559. configurable: true
  64560. });
  64561. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  64562. get: function () {
  64563. return this._dPadRight;
  64564. },
  64565. set: function (value) {
  64566. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  64567. },
  64568. enumerable: true,
  64569. configurable: true
  64570. });
  64571. Xbox360Pad.prototype.update = function () {
  64572. _super.prototype.update.call(this);
  64573. if (this._isXboxOnePad) {
  64574. this.buttonA = this.browserGamepad.buttons[0].value;
  64575. this.buttonB = this.browserGamepad.buttons[1].value;
  64576. this.buttonX = this.browserGamepad.buttons[2].value;
  64577. this.buttonY = this.browserGamepad.buttons[3].value;
  64578. this.buttonLB = this.browserGamepad.buttons[4].value;
  64579. this.buttonRB = this.browserGamepad.buttons[5].value;
  64580. this.leftTrigger = this.browserGamepad.axes[2];
  64581. this.rightTrigger = this.browserGamepad.axes[5];
  64582. this.buttonBack = this.browserGamepad.buttons[9].value;
  64583. this.buttonStart = this.browserGamepad.buttons[8].value;
  64584. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  64585. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  64586. this.dPadUp = this.browserGamepad.buttons[11].value;
  64587. this.dPadDown = this.browserGamepad.buttons[12].value;
  64588. this.dPadLeft = this.browserGamepad.buttons[13].value;
  64589. this.dPadRight = this.browserGamepad.buttons[14].value;
  64590. }
  64591. else {
  64592. this.buttonA = this.browserGamepad.buttons[0].value;
  64593. this.buttonB = this.browserGamepad.buttons[1].value;
  64594. this.buttonX = this.browserGamepad.buttons[2].value;
  64595. this.buttonY = this.browserGamepad.buttons[3].value;
  64596. this.buttonLB = this.browserGamepad.buttons[4].value;
  64597. this.buttonRB = this.browserGamepad.buttons[5].value;
  64598. this.leftTrigger = this.browserGamepad.buttons[6].value;
  64599. this.rightTrigger = this.browserGamepad.buttons[7].value;
  64600. this.buttonBack = this.browserGamepad.buttons[8].value;
  64601. this.buttonStart = this.browserGamepad.buttons[9].value;
  64602. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  64603. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  64604. this.dPadUp = this.browserGamepad.buttons[12].value;
  64605. this.dPadDown = this.browserGamepad.buttons[13].value;
  64606. this.dPadLeft = this.browserGamepad.buttons[14].value;
  64607. this.dPadRight = this.browserGamepad.buttons[15].value;
  64608. }
  64609. };
  64610. Xbox360Pad.prototype.dispose = function () {
  64611. _super.prototype.dispose.call(this);
  64612. this.onButtonDownObservable.clear();
  64613. this.onButtonUpObservable.clear();
  64614. this.onPadDownObservable.clear();
  64615. this.onPadUpObservable.clear();
  64616. };
  64617. return Xbox360Pad;
  64618. }(BABYLON.Gamepad));
  64619. BABYLON.Xbox360Pad = Xbox360Pad;
  64620. })(BABYLON || (BABYLON = {}));
  64621. //# sourceMappingURL=babylon.xboxGamepad.js.map
  64622. var BABYLON;
  64623. (function (BABYLON) {
  64624. var PoseEnabledControllerType;
  64625. (function (PoseEnabledControllerType) {
  64626. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  64627. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  64628. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  64629. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  64630. /**
  64631. * Google Daydream
  64632. */
  64633. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  64634. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  64635. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  64636. var PoseEnabledControllerHelper = /** @class */ (function () {
  64637. function PoseEnabledControllerHelper() {
  64638. }
  64639. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  64640. // Oculus Touch
  64641. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  64642. return new BABYLON.OculusTouchController(vrGamepad);
  64643. }
  64644. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  64645. return new BABYLON.WindowsMotionController(vrGamepad);
  64646. }
  64647. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  64648. return new BABYLON.ViveController(vrGamepad);
  64649. }
  64650. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  64651. return new BABYLON.GearVRController(vrGamepad);
  64652. }
  64653. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  64654. return new BABYLON.DaydreamController(vrGamepad);
  64655. }
  64656. else {
  64657. return new BABYLON.GenericController(vrGamepad);
  64658. }
  64659. };
  64660. return PoseEnabledControllerHelper;
  64661. }());
  64662. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  64663. var PoseEnabledController = /** @class */ (function (_super) {
  64664. __extends(PoseEnabledController, _super);
  64665. function PoseEnabledController(browserGamepad) {
  64666. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  64667. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  64668. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  64669. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  64670. // Represents device position and rotation in babylon space
  64671. _this.devicePosition = BABYLON.Vector3.Zero();
  64672. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  64673. _this.deviceScaleFactor = 1;
  64674. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  64675. _this._deviceToWorld = BABYLON.Matrix.Identity();
  64676. /**
  64677. * Node to be used when casting a ray from the controller
  64678. */
  64679. _this._pointingPoseNode = null;
  64680. _this._workingMatrix = BABYLON.Matrix.Identity();
  64681. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  64682. _this.controllerType = PoseEnabledControllerType.GENERIC;
  64683. _this.position = BABYLON.Vector3.Zero();
  64684. _this.rotationQuaternion = new BABYLON.Quaternion();
  64685. _this._calculatedPosition = BABYLON.Vector3.Zero();
  64686. _this._calculatedRotation = new BABYLON.Quaternion();
  64687. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  64688. return _this;
  64689. }
  64690. PoseEnabledController.prototype.update = function () {
  64691. _super.prototype.update.call(this);
  64692. var pose = this.browserGamepad.pose;
  64693. this.updateFromDevice(pose);
  64694. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  64695. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  64696. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  64697. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  64698. if (this._mesh) {
  64699. this._mesh.position.copyFrom(this.devicePosition);
  64700. if (this._mesh.rotationQuaternion) {
  64701. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64702. }
  64703. }
  64704. };
  64705. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  64706. if (poseData) {
  64707. this.rawPose = poseData;
  64708. if (poseData.position) {
  64709. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  64710. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  64711. this._deviceRoomPosition.z *= -1;
  64712. }
  64713. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  64714. this._calculatedPosition.addInPlace(this.position);
  64715. }
  64716. var pose = this.rawPose;
  64717. if (poseData.orientation && pose.orientation) {
  64718. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  64719. if (this._mesh) {
  64720. if (this._mesh.getScene().useRightHandedSystem) {
  64721. this._deviceRoomRotationQuaternion.z *= -1;
  64722. this._deviceRoomRotationQuaternion.w *= -1;
  64723. }
  64724. else {
  64725. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  64726. }
  64727. }
  64728. // if the camera is set, rotate to the camera's rotation
  64729. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  64730. }
  64731. }
  64732. };
  64733. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  64734. if (this._mesh) {
  64735. this._mesh.parent = null;
  64736. }
  64737. this._mesh = mesh;
  64738. if (this._poseControlledCamera) {
  64739. this._mesh.parent = this._poseControlledCamera;
  64740. }
  64741. if (!this._mesh.rotationQuaternion) {
  64742. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  64743. }
  64744. };
  64745. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  64746. this._poseControlledCamera = camera;
  64747. if (this._mesh) {
  64748. this._mesh.parent = this._poseControlledCamera;
  64749. }
  64750. };
  64751. PoseEnabledController.prototype.dispose = function () {
  64752. if (this._mesh) {
  64753. this._mesh.dispose();
  64754. }
  64755. this._mesh = null;
  64756. _super.prototype.dispose.call(this);
  64757. };
  64758. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  64759. get: function () {
  64760. return this._mesh;
  64761. },
  64762. enumerable: true,
  64763. configurable: true
  64764. });
  64765. PoseEnabledController.prototype.getForwardRay = function (length) {
  64766. if (length === void 0) { length = 100; }
  64767. if (!this.mesh) {
  64768. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  64769. }
  64770. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  64771. var origin = m.getTranslation();
  64772. var forward = new BABYLON.Vector3(0, 0, -1);
  64773. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64774. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64775. return new BABYLON.Ray(origin, direction, length);
  64776. };
  64777. /**
  64778. * Name of the child mesh that can be used to cast a ray from the controller
  64779. */
  64780. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  64781. return PoseEnabledController;
  64782. }(BABYLON.Gamepad));
  64783. BABYLON.PoseEnabledController = PoseEnabledController;
  64784. })(BABYLON || (BABYLON = {}));
  64785. //# sourceMappingURL=babylon.poseEnabledController.js.map
  64786. var BABYLON;
  64787. (function (BABYLON) {
  64788. var WebVRController = /** @class */ (function (_super) {
  64789. __extends(WebVRController, _super);
  64790. function WebVRController(vrGamepad) {
  64791. var _this = _super.call(this, vrGamepad) || this;
  64792. // Observables
  64793. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  64794. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  64795. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  64796. _this.onPadStateChangedObservable = new BABYLON.Observable();
  64797. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  64798. _this.pad = { x: 0, y: 0 };
  64799. // avoid GC, store state in a tmp object
  64800. _this._changes = {
  64801. pressChanged: false,
  64802. touchChanged: false,
  64803. valueChanged: false,
  64804. changed: false
  64805. };
  64806. _this._buttons = new Array(vrGamepad.buttons.length);
  64807. _this.hand = vrGamepad.hand;
  64808. return _this;
  64809. }
  64810. WebVRController.prototype.onButtonStateChange = function (callback) {
  64811. this._onButtonStateChange = callback;
  64812. };
  64813. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  64814. get: function () {
  64815. return this._defaultModel;
  64816. },
  64817. enumerable: true,
  64818. configurable: true
  64819. });
  64820. WebVRController.prototype.update = function () {
  64821. _super.prototype.update.call(this);
  64822. for (var index = 0; index < this._buttons.length; index++) {
  64823. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  64824. }
  64825. ;
  64826. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  64827. this.pad.x = this.leftStick.x;
  64828. this.pad.y = this.leftStick.y;
  64829. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  64830. }
  64831. };
  64832. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  64833. if (!newState) {
  64834. newState = {
  64835. pressed: false,
  64836. touched: false,
  64837. value: 0
  64838. };
  64839. }
  64840. if (!currentState) {
  64841. this._buttons[buttonIndex] = {
  64842. pressed: newState.pressed,
  64843. touched: newState.touched,
  64844. value: newState.value
  64845. };
  64846. return;
  64847. }
  64848. this._checkChanges(newState, currentState);
  64849. if (this._changes.changed) {
  64850. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  64851. this._handleButtonChange(buttonIndex, newState, this._changes);
  64852. }
  64853. this._buttons[buttonIndex].pressed = newState.pressed;
  64854. this._buttons[buttonIndex].touched = newState.touched;
  64855. // oculus triggers are never 0, thou not touched.
  64856. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  64857. };
  64858. WebVRController.prototype._checkChanges = function (newState, currentState) {
  64859. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  64860. this._changes.touchChanged = newState.touched !== currentState.touched;
  64861. this._changes.valueChanged = newState.value !== currentState.value;
  64862. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  64863. return this._changes;
  64864. };
  64865. WebVRController.prototype.dispose = function () {
  64866. _super.prototype.dispose.call(this);
  64867. this.onTriggerStateChangedObservable.clear();
  64868. this.onMainButtonStateChangedObservable.clear();
  64869. this.onSecondaryButtonStateChangedObservable.clear();
  64870. this.onPadStateChangedObservable.clear();
  64871. this.onPadValuesChangedObservable.clear();
  64872. };
  64873. return WebVRController;
  64874. }(BABYLON.PoseEnabledController));
  64875. BABYLON.WebVRController = WebVRController;
  64876. })(BABYLON || (BABYLON = {}));
  64877. //# sourceMappingURL=babylon.webVRController.js.map
  64878. var BABYLON;
  64879. (function (BABYLON) {
  64880. var OculusTouchController = /** @class */ (function (_super) {
  64881. __extends(OculusTouchController, _super);
  64882. function OculusTouchController(vrGamepad) {
  64883. var _this = _super.call(this, vrGamepad) || this;
  64884. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  64885. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  64886. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  64887. return _this;
  64888. }
  64889. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64890. var _this = this;
  64891. var meshName;
  64892. // Hand
  64893. if (this.hand === 'left') {
  64894. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  64895. }
  64896. else {
  64897. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  64898. }
  64899. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  64900. /*
  64901. Parent Mesh name: oculus_touch_left
  64902. - body
  64903. - trigger
  64904. - thumbstick
  64905. - grip
  64906. - button_y
  64907. - button_x
  64908. - button_enter
  64909. */
  64910. _this._defaultModel = newMeshes[1];
  64911. _this.attachToMesh(_this._defaultModel);
  64912. if (meshLoaded) {
  64913. meshLoaded(_this._defaultModel);
  64914. }
  64915. });
  64916. };
  64917. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  64918. // helper getters for left and right hand.
  64919. get: function () {
  64920. if (this.hand === 'right') {
  64921. return this.onMainButtonStateChangedObservable;
  64922. }
  64923. else {
  64924. throw new Error('No A button on left hand');
  64925. }
  64926. },
  64927. enumerable: true,
  64928. configurable: true
  64929. });
  64930. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  64931. get: function () {
  64932. if (this.hand === 'right') {
  64933. return this.onSecondaryButtonStateChangedObservable;
  64934. }
  64935. else {
  64936. throw new Error('No B button on left hand');
  64937. }
  64938. },
  64939. enumerable: true,
  64940. configurable: true
  64941. });
  64942. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  64943. get: function () {
  64944. if (this.hand === 'left') {
  64945. return this.onMainButtonStateChangedObservable;
  64946. }
  64947. else {
  64948. throw new Error('No X button on right hand');
  64949. }
  64950. },
  64951. enumerable: true,
  64952. configurable: true
  64953. });
  64954. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  64955. get: function () {
  64956. if (this.hand === 'left') {
  64957. return this.onSecondaryButtonStateChangedObservable;
  64958. }
  64959. else {
  64960. throw new Error('No Y button on right hand');
  64961. }
  64962. },
  64963. enumerable: true,
  64964. configurable: true
  64965. });
  64966. /*
  64967. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  64968. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  64969. 2) secondary trigger (same)
  64970. 3) A (right) X (left), touch, pressed = value
  64971. 4) B / Y
  64972. 5) thumb rest
  64973. */
  64974. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64975. var notifyObject = state; //{ state: state, changes: changes };
  64976. var triggerDirection = this.hand === 'right' ? -1 : 1;
  64977. switch (buttonIdx) {
  64978. case 0:
  64979. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64980. return;
  64981. case 1:// index trigger
  64982. if (this._defaultModel) {
  64983. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  64984. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  64985. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  64986. }
  64987. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64988. return;
  64989. case 2:// secondary trigger
  64990. if (this._defaultModel) {
  64991. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  64992. }
  64993. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  64994. return;
  64995. case 3:
  64996. if (this._defaultModel) {
  64997. if (notifyObject.pressed) {
  64998. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  64999. }
  65000. else {
  65001. (this._defaultModel.getChildren()[1]).position.y = 0;
  65002. }
  65003. }
  65004. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65005. return;
  65006. case 4:
  65007. if (this._defaultModel) {
  65008. if (notifyObject.pressed) {
  65009. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65010. }
  65011. else {
  65012. (this._defaultModel.getChildren()[2]).position.y = 0;
  65013. }
  65014. }
  65015. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65016. return;
  65017. case 5:
  65018. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  65019. return;
  65020. }
  65021. };
  65022. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  65023. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  65024. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  65025. return OculusTouchController;
  65026. }(BABYLON.WebVRController));
  65027. BABYLON.OculusTouchController = OculusTouchController;
  65028. })(BABYLON || (BABYLON = {}));
  65029. //# sourceMappingURL=babylon.oculusTouchController.js.map
  65030. var BABYLON;
  65031. (function (BABYLON) {
  65032. var ViveController = /** @class */ (function (_super) {
  65033. __extends(ViveController, _super);
  65034. function ViveController(vrGamepad) {
  65035. var _this = _super.call(this, vrGamepad) || this;
  65036. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  65037. _this._invertLeftStickY = true;
  65038. return _this;
  65039. }
  65040. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65041. var _this = this;
  65042. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  65043. /*
  65044. Parent Mesh name: ViveWand
  65045. - body
  65046. - r_gripper
  65047. - l_gripper
  65048. - menu_button
  65049. - system_button
  65050. - trackpad
  65051. - trigger
  65052. - LED
  65053. */
  65054. _this._defaultModel = newMeshes[1];
  65055. _this.attachToMesh(_this._defaultModel);
  65056. if (meshLoaded) {
  65057. meshLoaded(_this._defaultModel);
  65058. }
  65059. });
  65060. };
  65061. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  65062. get: function () {
  65063. return this.onMainButtonStateChangedObservable;
  65064. },
  65065. enumerable: true,
  65066. configurable: true
  65067. });
  65068. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  65069. get: function () {
  65070. return this.onMainButtonStateChangedObservable;
  65071. },
  65072. enumerable: true,
  65073. configurable: true
  65074. });
  65075. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  65076. get: function () {
  65077. return this.onSecondaryButtonStateChangedObservable;
  65078. },
  65079. enumerable: true,
  65080. configurable: true
  65081. });
  65082. /**
  65083. * Vive mapping:
  65084. * 0: touchpad
  65085. * 1: trigger
  65086. * 2: left AND right buttons
  65087. * 3: menu button
  65088. */
  65089. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65090. var notifyObject = state; //{ state: state, changes: changes };
  65091. switch (buttonIdx) {
  65092. case 0:
  65093. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65094. return;
  65095. case 1:// index trigger
  65096. if (this._defaultModel) {
  65097. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  65098. }
  65099. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65100. return;
  65101. case 2:// left AND right button
  65102. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65103. return;
  65104. case 3:
  65105. if (this._defaultModel) {
  65106. if (notifyObject.pressed) {
  65107. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65108. }
  65109. else {
  65110. (this._defaultModel.getChildren()[2]).position.y = 0;
  65111. }
  65112. }
  65113. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65114. return;
  65115. }
  65116. };
  65117. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  65118. ViveController.MODEL_FILENAME = 'wand.babylon';
  65119. return ViveController;
  65120. }(BABYLON.WebVRController));
  65121. BABYLON.ViveController = ViveController;
  65122. })(BABYLON || (BABYLON = {}));
  65123. //# sourceMappingURL=babylon.viveController.js.map
  65124. var BABYLON;
  65125. (function (BABYLON) {
  65126. var GenericController = /** @class */ (function (_super) {
  65127. __extends(GenericController, _super);
  65128. function GenericController(vrGamepad) {
  65129. return _super.call(this, vrGamepad) || this;
  65130. }
  65131. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65132. var _this = this;
  65133. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  65134. _this._defaultModel = newMeshes[1];
  65135. _this.attachToMesh(_this._defaultModel);
  65136. if (meshLoaded) {
  65137. meshLoaded(_this._defaultModel);
  65138. }
  65139. });
  65140. };
  65141. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65142. console.log("Button id: " + buttonIdx + "state: ");
  65143. console.dir(state);
  65144. };
  65145. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65146. GenericController.MODEL_FILENAME = 'generic.babylon';
  65147. return GenericController;
  65148. }(BABYLON.WebVRController));
  65149. BABYLON.GenericController = GenericController;
  65150. })(BABYLON || (BABYLON = {}));
  65151. //# sourceMappingURL=babylon.genericController.js.map
  65152. var BABYLON;
  65153. (function (BABYLON) {
  65154. var LoadedMeshInfo = /** @class */ (function () {
  65155. function LoadedMeshInfo() {
  65156. this.buttonMeshes = {};
  65157. this.axisMeshes = {};
  65158. }
  65159. return LoadedMeshInfo;
  65160. }());
  65161. var WindowsMotionController = /** @class */ (function (_super) {
  65162. __extends(WindowsMotionController, _super);
  65163. function WindowsMotionController(vrGamepad) {
  65164. var _this = _super.call(this, vrGamepad) || this;
  65165. _this._mapping = {
  65166. // Semantic button names
  65167. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  65168. // A mapping of the button name to glTF model node name
  65169. // that should be transformed by button value.
  65170. buttonMeshNames: {
  65171. 'trigger': 'SELECT',
  65172. 'menu': 'MENU',
  65173. 'grip': 'GRASP',
  65174. 'thumbstick': 'THUMBSTICK_PRESS',
  65175. 'trackpad': 'TOUCHPAD_PRESS'
  65176. },
  65177. // This mapping is used to translate from the Motion Controller to Babylon semantics
  65178. buttonObservableNames: {
  65179. 'trigger': 'onTriggerStateChangedObservable',
  65180. 'menu': 'onSecondaryButtonStateChangedObservable',
  65181. 'grip': 'onMainButtonStateChangedObservable',
  65182. 'thumbstick': 'onPadStateChangedObservable',
  65183. 'trackpad': 'onTrackpadChangedObservable'
  65184. },
  65185. // A mapping of the axis name to glTF model node name
  65186. // that should be transformed by axis value.
  65187. // This array mirrors the browserGamepad.axes array, such that
  65188. // the mesh corresponding to axis 0 is in this array index 0.
  65189. axisMeshNames: [
  65190. 'THUMBSTICK_X',
  65191. 'THUMBSTICK_Y',
  65192. 'TOUCHPAD_TOUCH_X',
  65193. 'TOUCHPAD_TOUCH_Y'
  65194. ],
  65195. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  65196. };
  65197. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  65198. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  65199. _this.trackpad = { x: 0, y: 0 };
  65200. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  65201. _this._loadedMeshInfo = null;
  65202. return _this;
  65203. }
  65204. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  65205. get: function () {
  65206. return this.onTriggerStateChangedObservable;
  65207. },
  65208. enumerable: true,
  65209. configurable: true
  65210. });
  65211. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  65212. get: function () {
  65213. return this.onSecondaryButtonStateChangedObservable;
  65214. },
  65215. enumerable: true,
  65216. configurable: true
  65217. });
  65218. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  65219. get: function () {
  65220. return this.onMainButtonStateChangedObservable;
  65221. },
  65222. enumerable: true,
  65223. configurable: true
  65224. });
  65225. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  65226. get: function () {
  65227. return this.onPadStateChangedObservable;
  65228. },
  65229. enumerable: true,
  65230. configurable: true
  65231. });
  65232. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  65233. get: function () {
  65234. return this.onTrackpadChangedObservable;
  65235. },
  65236. enumerable: true,
  65237. configurable: true
  65238. });
  65239. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  65240. get: function () {
  65241. return this.onTrackpadValuesChangedObservable;
  65242. },
  65243. enumerable: true,
  65244. configurable: true
  65245. });
  65246. /**
  65247. * Called once per frame by the engine.
  65248. */
  65249. WindowsMotionController.prototype.update = function () {
  65250. _super.prototype.update.call(this);
  65251. if (this.browserGamepad.axes) {
  65252. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  65253. this.trackpad.x = this.browserGamepad["axes"][2];
  65254. this.trackpad.y = this.browserGamepad["axes"][3];
  65255. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  65256. }
  65257. // Only need to animate axes if there is a loaded mesh
  65258. if (this._loadedMeshInfo) {
  65259. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  65260. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  65261. }
  65262. }
  65263. }
  65264. };
  65265. /**
  65266. * Called once for each button that changed state since the last frame
  65267. * @param buttonIdx Which button index changed
  65268. * @param state New state of the button
  65269. * @param changes Which properties on the state changed since last frame
  65270. */
  65271. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65272. var buttonName = this._mapping.buttons[buttonIdx];
  65273. if (!buttonName) {
  65274. return;
  65275. }
  65276. // Only emit events for buttons that we know how to map from index to name
  65277. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  65278. if (observable) {
  65279. observable.notifyObservers(state);
  65280. }
  65281. this.lerpButtonTransform(buttonName, state.value);
  65282. };
  65283. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  65284. // If there is no loaded mesh, there is nothing to transform.
  65285. if (!this._loadedMeshInfo) {
  65286. return;
  65287. }
  65288. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  65289. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65290. return;
  65291. }
  65292. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  65293. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  65294. };
  65295. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  65296. if (!this._loadedMeshInfo) {
  65297. return;
  65298. }
  65299. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  65300. if (!meshInfo) {
  65301. return;
  65302. }
  65303. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65304. return;
  65305. }
  65306. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  65307. var lerpValue = axisValue * 0.5 + 0.5;
  65308. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  65309. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  65310. };
  65311. /**
  65312. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  65313. * @param scene scene in which to add meshes
  65314. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  65315. */
  65316. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  65317. var _this = this;
  65318. if (forceDefault === void 0) { forceDefault = false; }
  65319. var path;
  65320. var filename;
  65321. // Checking if GLB loader is present
  65322. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  65323. // Determine the device specific folder based on the ID suffix
  65324. var device = 'default';
  65325. if (this.id && !forceDefault) {
  65326. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  65327. device = ((match && match[0]) || device);
  65328. }
  65329. // Hand
  65330. if (this.hand === 'left') {
  65331. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  65332. }
  65333. else {
  65334. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  65335. }
  65336. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  65337. }
  65338. else {
  65339. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  65340. path = BABYLON.GenericController.MODEL_BASE_URL;
  65341. filename = BABYLON.GenericController.MODEL_FILENAME;
  65342. }
  65343. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  65344. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  65345. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  65346. if (!_this._loadedMeshInfo) {
  65347. return;
  65348. }
  65349. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  65350. _this.attachToMesh(_this._defaultModel);
  65351. if (meshLoaded) {
  65352. meshLoaded(_this._defaultModel);
  65353. }
  65354. }, null, function (scene, message) {
  65355. BABYLON.Tools.Log(message);
  65356. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  65357. if (!forceDefault) {
  65358. _this.initControllerMesh(scene, meshLoaded, true);
  65359. }
  65360. });
  65361. };
  65362. /**
  65363. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  65364. * can be transformed by button presses and axes values, based on this._mapping.
  65365. *
  65366. * @param scene scene in which the meshes exist
  65367. * @param meshes list of meshes that make up the controller model to process
  65368. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  65369. */
  65370. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  65371. var loadedMeshInfo = null;
  65372. // Create a new mesh to contain the glTF hierarchy
  65373. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  65374. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  65375. var childMesh = null;
  65376. for (var i = 0; i < meshes.length; i++) {
  65377. var mesh = meshes[i];
  65378. if (!mesh.parent) {
  65379. // Exclude controller meshes from picking results
  65380. mesh.isPickable = false;
  65381. // Handle root node, attach to the new parentMesh
  65382. childMesh = mesh;
  65383. break;
  65384. }
  65385. }
  65386. if (childMesh) {
  65387. childMesh.setParent(parentMesh);
  65388. // Create our mesh info. Note that this method will always return non-null.
  65389. loadedMeshInfo = this.createMeshInfo(parentMesh);
  65390. }
  65391. else {
  65392. BABYLON.Tools.Warn('Could not find root node in model file.');
  65393. }
  65394. return loadedMeshInfo;
  65395. };
  65396. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  65397. var loadedMeshInfo = new LoadedMeshInfo();
  65398. var i;
  65399. loadedMeshInfo.rootNode = rootNode;
  65400. // Reset the caches
  65401. loadedMeshInfo.buttonMeshes = {};
  65402. loadedMeshInfo.axisMeshes = {};
  65403. // Button Meshes
  65404. for (i = 0; i < this._mapping.buttons.length; i++) {
  65405. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  65406. if (!buttonMeshName) {
  65407. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  65408. continue;
  65409. }
  65410. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  65411. if (!buttonMesh) {
  65412. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  65413. continue;
  65414. }
  65415. var buttonMeshInfo = {
  65416. index: i,
  65417. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  65418. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  65419. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  65420. };
  65421. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  65422. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  65423. }
  65424. else {
  65425. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  65426. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  65427. '(VALUE: ' + !!buttonMeshInfo.value +
  65428. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  65429. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  65430. ')');
  65431. }
  65432. }
  65433. // Axis Meshes
  65434. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  65435. var axisMeshName = this._mapping.axisMeshNames[i];
  65436. if (!axisMeshName) {
  65437. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  65438. continue;
  65439. }
  65440. var axisMesh = getChildByName(rootNode, axisMeshName);
  65441. if (!axisMesh) {
  65442. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  65443. continue;
  65444. }
  65445. var axisMeshInfo = {
  65446. index: i,
  65447. value: getImmediateChildByName(axisMesh, 'VALUE'),
  65448. min: getImmediateChildByName(axisMesh, 'MIN'),
  65449. max: getImmediateChildByName(axisMesh, 'MAX')
  65450. };
  65451. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  65452. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  65453. }
  65454. else {
  65455. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  65456. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  65457. '(VALUE: ' + !!axisMeshInfo.value +
  65458. ', MIN: ' + !!axisMeshInfo.min +
  65459. ', MAX:' + !!axisMeshInfo.max +
  65460. ')');
  65461. }
  65462. }
  65463. // Pointing Ray
  65464. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  65465. if (!loadedMeshInfo.pointingPoseNode) {
  65466. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  65467. }
  65468. return loadedMeshInfo;
  65469. // Look through all children recursively. This will return null if no mesh exists with the given name.
  65470. function getChildByName(node, name) {
  65471. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  65472. }
  65473. // Look through only immediate children. This will return null if no mesh exists with the given name.
  65474. function getImmediateChildByName(node, name) {
  65475. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  65476. }
  65477. };
  65478. WindowsMotionController.prototype.getForwardRay = function (length) {
  65479. if (length === void 0) { length = 100; }
  65480. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  65481. return _super.prototype.getForwardRay.call(this, length);
  65482. }
  65483. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  65484. var origin = m.getTranslation();
  65485. var forward = new BABYLON.Vector3(0, 0, -1);
  65486. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65487. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65488. return new BABYLON.Ray(origin, direction, length);
  65489. };
  65490. WindowsMotionController.prototype.dispose = function () {
  65491. _super.prototype.dispose.call(this);
  65492. this.onTrackpadChangedObservable.clear();
  65493. };
  65494. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  65495. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  65496. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  65497. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  65498. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  65499. return WindowsMotionController;
  65500. }(BABYLON.WebVRController));
  65501. BABYLON.WindowsMotionController = WindowsMotionController;
  65502. })(BABYLON || (BABYLON = {}));
  65503. //# sourceMappingURL=babylon.windowsMotionController.js.map
  65504. var BABYLON;
  65505. (function (BABYLON) {
  65506. var GearVRController = /** @class */ (function (_super) {
  65507. __extends(GearVRController, _super);
  65508. function GearVRController(vrGamepad) {
  65509. var _this = _super.call(this, vrGamepad) || this;
  65510. _this._buttonIndexToObservableNameMap = [
  65511. 'onTrackpadChangedObservable',
  65512. 'onTriggerStateChangedObservable' // Trigger
  65513. ];
  65514. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  65515. return _this;
  65516. }
  65517. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65518. var _this = this;
  65519. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  65520. _this._defaultModel = newMeshes[1];
  65521. _this.attachToMesh(_this._defaultModel);
  65522. if (meshLoaded) {
  65523. meshLoaded(_this._defaultModel);
  65524. }
  65525. });
  65526. };
  65527. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65528. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  65529. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  65530. // Only emit events for buttons that we know how to map from index to observable
  65531. var observable = this[observableName];
  65532. if (observable) {
  65533. observable.notifyObservers(state);
  65534. }
  65535. }
  65536. };
  65537. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65538. GearVRController.MODEL_FILENAME = 'generic.babylon';
  65539. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  65540. return GearVRController;
  65541. }(BABYLON.WebVRController));
  65542. BABYLON.GearVRController = GearVRController;
  65543. })(BABYLON || (BABYLON = {}));
  65544. //# sourceMappingURL=babylon.gearVRController.js.map
  65545. var BABYLON;
  65546. (function (BABYLON) {
  65547. /**
  65548. * Google Daydream controller
  65549. */
  65550. var DaydreamController = /** @class */ (function (_super) {
  65551. __extends(DaydreamController, _super);
  65552. function DaydreamController(vrGamepad) {
  65553. var _this = _super.call(this, vrGamepad) || this;
  65554. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  65555. return _this;
  65556. }
  65557. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65558. var _this = this;
  65559. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  65560. _this._defaultModel = newMeshes[1];
  65561. _this.attachToMesh(_this._defaultModel);
  65562. if (meshLoaded) {
  65563. meshLoaded(_this._defaultModel);
  65564. }
  65565. });
  65566. };
  65567. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65568. // Daydream controller only has 1 GamepadButton (on the trackpad).
  65569. if (buttonIdx === 0) {
  65570. var observable = this.onTriggerStateChangedObservable;
  65571. if (observable) {
  65572. observable.notifyObservers(state);
  65573. }
  65574. }
  65575. else {
  65576. // If the app or home buttons are ever made available
  65577. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  65578. }
  65579. };
  65580. /**
  65581. * Base Url for the controller model.
  65582. */
  65583. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65584. /**
  65585. * File name for the controller model.
  65586. */
  65587. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  65588. /**
  65589. * Gamepad Id prefix used to identify Daydream Controller.
  65590. */
  65591. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  65592. return DaydreamController;
  65593. }(BABYLON.WebVRController));
  65594. BABYLON.DaydreamController = DaydreamController;
  65595. })(BABYLON || (BABYLON = {}));
  65596. //# sourceMappingURL=babylon.daydreamController.js.map
  65597. var BABYLON;
  65598. (function (BABYLON) {
  65599. var FollowCamera = /** @class */ (function (_super) {
  65600. __extends(FollowCamera, _super);
  65601. function FollowCamera(name, position, scene, lockedTarget) {
  65602. if (lockedTarget === void 0) { lockedTarget = null; }
  65603. var _this = _super.call(this, name, position, scene) || this;
  65604. _this.radius = 12;
  65605. _this.rotationOffset = 0;
  65606. _this.heightOffset = 4;
  65607. _this.cameraAcceleration = 0.05;
  65608. _this.maxCameraSpeed = 20;
  65609. _this.lockedTarget = lockedTarget;
  65610. return _this;
  65611. }
  65612. FollowCamera.prototype.getRadians = function (degrees) {
  65613. return degrees * Math.PI / 180;
  65614. };
  65615. FollowCamera.prototype.follow = function (cameraTarget) {
  65616. if (!cameraTarget)
  65617. return;
  65618. var yRotation;
  65619. if (cameraTarget.rotationQuaternion) {
  65620. var rotMatrix = new BABYLON.Matrix();
  65621. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  65622. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  65623. }
  65624. else {
  65625. yRotation = cameraTarget.rotation.y;
  65626. }
  65627. var radians = this.getRadians(this.rotationOffset) + yRotation;
  65628. var targetPosition = cameraTarget.getAbsolutePosition();
  65629. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  65630. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  65631. var dx = targetX - this.position.x;
  65632. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  65633. var dz = (targetZ) - this.position.z;
  65634. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  65635. var vy = dy * this.cameraAcceleration;
  65636. var vz = dz * this.cameraAcceleration * 2;
  65637. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  65638. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65639. }
  65640. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  65641. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65642. }
  65643. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  65644. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65645. }
  65646. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  65647. this.setTarget(targetPosition);
  65648. };
  65649. FollowCamera.prototype._checkInputs = function () {
  65650. _super.prototype._checkInputs.call(this);
  65651. if (this.lockedTarget) {
  65652. this.follow(this.lockedTarget);
  65653. }
  65654. };
  65655. FollowCamera.prototype.getClassName = function () {
  65656. return "FollowCamera";
  65657. };
  65658. __decorate([
  65659. BABYLON.serialize()
  65660. ], FollowCamera.prototype, "radius", void 0);
  65661. __decorate([
  65662. BABYLON.serialize()
  65663. ], FollowCamera.prototype, "rotationOffset", void 0);
  65664. __decorate([
  65665. BABYLON.serialize()
  65666. ], FollowCamera.prototype, "heightOffset", void 0);
  65667. __decorate([
  65668. BABYLON.serialize()
  65669. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  65670. __decorate([
  65671. BABYLON.serialize()
  65672. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  65673. __decorate([
  65674. BABYLON.serializeAsMeshReference("lockedTargetId")
  65675. ], FollowCamera.prototype, "lockedTarget", void 0);
  65676. return FollowCamera;
  65677. }(BABYLON.TargetCamera));
  65678. BABYLON.FollowCamera = FollowCamera;
  65679. var ArcFollowCamera = /** @class */ (function (_super) {
  65680. __extends(ArcFollowCamera, _super);
  65681. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  65682. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  65683. _this.alpha = alpha;
  65684. _this.beta = beta;
  65685. _this.radius = radius;
  65686. _this.target = target;
  65687. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  65688. _this.follow();
  65689. return _this;
  65690. }
  65691. ArcFollowCamera.prototype.follow = function () {
  65692. if (!this.target) {
  65693. return;
  65694. }
  65695. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  65696. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  65697. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  65698. var targetPosition = this.target.getAbsolutePosition();
  65699. this.position = targetPosition.add(this._cartesianCoordinates);
  65700. this.setTarget(targetPosition);
  65701. };
  65702. ArcFollowCamera.prototype._checkInputs = function () {
  65703. _super.prototype._checkInputs.call(this);
  65704. this.follow();
  65705. };
  65706. ArcFollowCamera.prototype.getClassName = function () {
  65707. return "ArcFollowCamera";
  65708. };
  65709. return ArcFollowCamera;
  65710. }(BABYLON.TargetCamera));
  65711. BABYLON.ArcFollowCamera = ArcFollowCamera;
  65712. })(BABYLON || (BABYLON = {}));
  65713. //# sourceMappingURL=babylon.followCamera.js.map
  65714. var BABYLON;
  65715. (function (BABYLON) {
  65716. // We're mainly based on the logic defined into the FreeCamera code
  65717. var UniversalCamera = /** @class */ (function (_super) {
  65718. __extends(UniversalCamera, _super);
  65719. //-- end properties for backward compatibility for inputs
  65720. function UniversalCamera(name, position, scene) {
  65721. var _this = _super.call(this, name, position, scene) || this;
  65722. _this.inputs.addGamepad();
  65723. return _this;
  65724. }
  65725. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  65726. //-- Begin properties for backward compatibility for inputs
  65727. get: function () {
  65728. var gamepad = this.inputs.attached["gamepad"];
  65729. if (gamepad)
  65730. return gamepad.gamepadAngularSensibility;
  65731. return 0;
  65732. },
  65733. set: function (value) {
  65734. var gamepad = this.inputs.attached["gamepad"];
  65735. if (gamepad)
  65736. gamepad.gamepadAngularSensibility = value;
  65737. },
  65738. enumerable: true,
  65739. configurable: true
  65740. });
  65741. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  65742. get: function () {
  65743. var gamepad = this.inputs.attached["gamepad"];
  65744. if (gamepad)
  65745. return gamepad.gamepadMoveSensibility;
  65746. return 0;
  65747. },
  65748. set: function (value) {
  65749. var gamepad = this.inputs.attached["gamepad"];
  65750. if (gamepad)
  65751. gamepad.gamepadMoveSensibility = value;
  65752. },
  65753. enumerable: true,
  65754. configurable: true
  65755. });
  65756. UniversalCamera.prototype.getClassName = function () {
  65757. return "UniversalCamera";
  65758. };
  65759. return UniversalCamera;
  65760. }(BABYLON.TouchCamera));
  65761. BABYLON.UniversalCamera = UniversalCamera;
  65762. })(BABYLON || (BABYLON = {}));
  65763. //# sourceMappingURL=babylon.universalCamera.js.map
  65764. var BABYLON;
  65765. (function (BABYLON) {
  65766. // We're mainly based on the logic defined into the FreeCamera code
  65767. var GamepadCamera = /** @class */ (function (_super) {
  65768. __extends(GamepadCamera, _super);
  65769. //-- end properties for backward compatibility for inputs
  65770. function GamepadCamera(name, position, scene) {
  65771. return _super.call(this, name, position, scene) || this;
  65772. }
  65773. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  65774. //-- Begin properties for backward compatibility for inputs
  65775. get: function () {
  65776. var gamepad = this.inputs.attached["gamepad"];
  65777. if (gamepad)
  65778. return gamepad.gamepadAngularSensibility;
  65779. return 0;
  65780. },
  65781. set: function (value) {
  65782. var gamepad = this.inputs.attached["gamepad"];
  65783. if (gamepad)
  65784. gamepad.gamepadAngularSensibility = value;
  65785. },
  65786. enumerable: true,
  65787. configurable: true
  65788. });
  65789. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  65790. get: function () {
  65791. var gamepad = this.inputs.attached["gamepad"];
  65792. if (gamepad)
  65793. return gamepad.gamepadMoveSensibility;
  65794. return 0;
  65795. },
  65796. set: function (value) {
  65797. var gamepad = this.inputs.attached["gamepad"];
  65798. if (gamepad)
  65799. gamepad.gamepadMoveSensibility = value;
  65800. },
  65801. enumerable: true,
  65802. configurable: true
  65803. });
  65804. GamepadCamera.prototype.getClassName = function () {
  65805. return "GamepadCamera";
  65806. };
  65807. return GamepadCamera;
  65808. }(BABYLON.UniversalCamera));
  65809. BABYLON.GamepadCamera = GamepadCamera;
  65810. })(BABYLON || (BABYLON = {}));
  65811. //# sourceMappingURL=babylon.gamepadCamera.js.map
  65812. var BABYLON;
  65813. (function (BABYLON) {
  65814. var PostProcessRenderPipelineManager = /** @class */ (function () {
  65815. function PostProcessRenderPipelineManager() {
  65816. this._renderPipelines = {};
  65817. }
  65818. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  65819. this._renderPipelines[renderPipeline._name] = renderPipeline;
  65820. };
  65821. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  65822. if (unique === void 0) { unique = false; }
  65823. var renderPipeline = this._renderPipelines[renderPipelineName];
  65824. if (!renderPipeline) {
  65825. return;
  65826. }
  65827. renderPipeline._attachCameras(cameras, unique);
  65828. };
  65829. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  65830. var renderPipeline = this._renderPipelines[renderPipelineName];
  65831. if (!renderPipeline) {
  65832. return;
  65833. }
  65834. renderPipeline._detachCameras(cameras);
  65835. };
  65836. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65837. var renderPipeline = this._renderPipelines[renderPipelineName];
  65838. if (!renderPipeline) {
  65839. return;
  65840. }
  65841. renderPipeline._enableEffect(renderEffectName, cameras);
  65842. };
  65843. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65844. var renderPipeline = this._renderPipelines[renderPipelineName];
  65845. if (!renderPipeline) {
  65846. return;
  65847. }
  65848. renderPipeline._disableEffect(renderEffectName, cameras);
  65849. };
  65850. PostProcessRenderPipelineManager.prototype.update = function () {
  65851. for (var renderPipelineName in this._renderPipelines) {
  65852. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65853. var pipeline = this._renderPipelines[renderPipelineName];
  65854. if (!pipeline.isSupported) {
  65855. pipeline.dispose();
  65856. delete this._renderPipelines[renderPipelineName];
  65857. }
  65858. else {
  65859. pipeline._update();
  65860. }
  65861. }
  65862. }
  65863. };
  65864. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  65865. for (var renderPipelineName in this._renderPipelines) {
  65866. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65867. var pipeline = this._renderPipelines[renderPipelineName];
  65868. pipeline._rebuild();
  65869. }
  65870. }
  65871. };
  65872. PostProcessRenderPipelineManager.prototype.dispose = function () {
  65873. for (var renderPipelineName in this._renderPipelines) {
  65874. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65875. var pipeline = this._renderPipelines[renderPipelineName];
  65876. pipeline.dispose();
  65877. }
  65878. }
  65879. };
  65880. return PostProcessRenderPipelineManager;
  65881. }());
  65882. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  65883. })(BABYLON || (BABYLON = {}));
  65884. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  65885. var BABYLON;
  65886. (function (BABYLON) {
  65887. /**
  65888. * This represents a set of one or more post processes in Babylon.
  65889. * A post process can be used to apply a shader to a texture after it is rendered.
  65890. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  65891. */
  65892. var PostProcessRenderEffect = /** @class */ (function () {
  65893. /**
  65894. * Instantiates a post process render effect.
  65895. * A post process can be used to apply a shader to a texture after it is rendered.
  65896. * @param engine The engine the effect is tied to
  65897. * @param name The name of the effect
  65898. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  65899. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  65900. */
  65901. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  65902. this._name = name;
  65903. this._singleInstance = singleInstance || true;
  65904. this._getPostProcesses = getPostProcesses;
  65905. this._cameras = {};
  65906. this._indicesForCamera = {};
  65907. this._postProcesses = {};
  65908. }
  65909. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  65910. /**
  65911. * Checks if all the post processes in the effect are supported.
  65912. */
  65913. get: function () {
  65914. for (var index in this._postProcesses) {
  65915. for (var ppIndex in this._postProcesses[index]) {
  65916. if (!this._postProcesses[index][ppIndex].isSupported) {
  65917. return false;
  65918. }
  65919. }
  65920. }
  65921. return true;
  65922. },
  65923. enumerable: true,
  65924. configurable: true
  65925. });
  65926. /**
  65927. * Updates the current state of the effect
  65928. */
  65929. PostProcessRenderEffect.prototype._update = function () {
  65930. };
  65931. /**
  65932. * Attaches the effect on cameras
  65933. * @param cameras The camera to attach to.
  65934. */
  65935. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  65936. var _this = this;
  65937. var cameraKey;
  65938. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65939. if (!cams) {
  65940. return;
  65941. }
  65942. for (var i = 0; i < cams.length; i++) {
  65943. var camera = cams[i];
  65944. var cameraName = camera.name;
  65945. if (this._singleInstance) {
  65946. cameraKey = 0;
  65947. }
  65948. else {
  65949. cameraKey = cameraName;
  65950. }
  65951. if (!this._postProcesses[cameraKey]) {
  65952. var postProcess = this._getPostProcesses();
  65953. if (postProcess) {
  65954. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  65955. }
  65956. }
  65957. if (!this._indicesForCamera[cameraName]) {
  65958. this._indicesForCamera[cameraName] = [];
  65959. }
  65960. this._postProcesses[cameraKey].forEach(function (postProcess) {
  65961. var index = camera.attachPostProcess(postProcess);
  65962. _this._indicesForCamera[cameraName].push(index);
  65963. });
  65964. if (!this._cameras[cameraName]) {
  65965. this._cameras[cameraName] = camera;
  65966. }
  65967. }
  65968. };
  65969. /**
  65970. * Detatches the effect on cameras
  65971. * @param cameras The camera to detatch from.
  65972. */
  65973. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  65974. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65975. if (!cams) {
  65976. return;
  65977. }
  65978. for (var i = 0; i < cams.length; i++) {
  65979. var camera = cams[i];
  65980. var cameraName = camera.name;
  65981. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65982. camera.detachPostProcess(postProcess);
  65983. });
  65984. if (this._cameras[cameraName]) {
  65985. //this._indicesForCamera.splice(index, 1);
  65986. this._cameras[cameraName] = null;
  65987. }
  65988. }
  65989. };
  65990. /**
  65991. * Enables the effect on given cameras
  65992. * @param cameras The camera to enable.
  65993. */
  65994. PostProcessRenderEffect.prototype._enable = function (cameras) {
  65995. var _this = this;
  65996. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65997. if (!cams) {
  65998. return;
  65999. }
  66000. for (var i = 0; i < cams.length; i++) {
  66001. var camera = cams[i];
  66002. var cameraName = camera.name;
  66003. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  66004. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  66005. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66006. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  66007. });
  66008. }
  66009. }
  66010. }
  66011. };
  66012. /**
  66013. * Disables the effect on the given cameras
  66014. * @param cameras The camera to disable.
  66015. */
  66016. PostProcessRenderEffect.prototype._disable = function (cameras) {
  66017. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66018. if (!cams) {
  66019. return;
  66020. }
  66021. for (var i = 0; i < cams.length; i++) {
  66022. var camera = cams[i];
  66023. var cameraName = camera.name;
  66024. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66025. camera.detachPostProcess(postProcess);
  66026. });
  66027. }
  66028. };
  66029. /**
  66030. * Gets a list of the post processes contained in the effect.
  66031. * @param camera The camera to get the post processes on.
  66032. * @returns The list of the post processes in the effect.
  66033. */
  66034. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  66035. if (this._singleInstance) {
  66036. return this._postProcesses[0];
  66037. }
  66038. else {
  66039. if (!camera) {
  66040. return null;
  66041. }
  66042. return this._postProcesses[camera.name];
  66043. }
  66044. };
  66045. return PostProcessRenderEffect;
  66046. }());
  66047. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  66048. })(BABYLON || (BABYLON = {}));
  66049. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  66050. var BABYLON;
  66051. (function (BABYLON) {
  66052. var PostProcessRenderPipeline = /** @class */ (function () {
  66053. function PostProcessRenderPipeline(engine, name) {
  66054. this.engine = engine;
  66055. this._name = name;
  66056. this._renderEffects = {};
  66057. this._renderEffectsForIsolatedPass = new Array();
  66058. this._cameras = [];
  66059. }
  66060. PostProcessRenderPipeline.prototype.getClassName = function () {
  66061. return "PostProcessRenderPipeline";
  66062. };
  66063. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  66064. get: function () {
  66065. for (var renderEffectName in this._renderEffects) {
  66066. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66067. if (!this._renderEffects[renderEffectName].isSupported) {
  66068. return false;
  66069. }
  66070. }
  66071. }
  66072. return true;
  66073. },
  66074. enumerable: true,
  66075. configurable: true
  66076. });
  66077. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  66078. this._renderEffects[renderEffect._name] = renderEffect;
  66079. };
  66080. // private
  66081. PostProcessRenderPipeline.prototype._rebuild = function () {
  66082. };
  66083. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  66084. var renderEffects = this._renderEffects[renderEffectName];
  66085. if (!renderEffects) {
  66086. return;
  66087. }
  66088. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66089. };
  66090. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  66091. var renderEffects = this._renderEffects[renderEffectName];
  66092. if (!renderEffects) {
  66093. return;
  66094. }
  66095. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66096. };
  66097. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  66098. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66099. if (!cams) {
  66100. return;
  66101. }
  66102. var indicesToDelete = [];
  66103. var i;
  66104. for (i = 0; i < cams.length; i++) {
  66105. var camera = cams[i];
  66106. var cameraName = camera.name;
  66107. if (this._cameras.indexOf(camera) === -1) {
  66108. this._cameras[cameraName] = camera;
  66109. }
  66110. else if (unique) {
  66111. indicesToDelete.push(i);
  66112. }
  66113. }
  66114. for (i = 0; i < indicesToDelete.length; i++) {
  66115. cameras.splice(indicesToDelete[i], 1);
  66116. }
  66117. for (var renderEffectName in this._renderEffects) {
  66118. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66119. this._renderEffects[renderEffectName]._attachCameras(cams);
  66120. }
  66121. }
  66122. };
  66123. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  66124. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66125. if (!cams) {
  66126. return;
  66127. }
  66128. for (var renderEffectName in this._renderEffects) {
  66129. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66130. this._renderEffects[renderEffectName]._detachCameras(cams);
  66131. }
  66132. }
  66133. for (var i = 0; i < cams.length; i++) {
  66134. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  66135. }
  66136. };
  66137. PostProcessRenderPipeline.prototype._update = function () {
  66138. for (var renderEffectName in this._renderEffects) {
  66139. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66140. this._renderEffects[renderEffectName]._update();
  66141. }
  66142. }
  66143. for (var i = 0; i < this._cameras.length; i++) {
  66144. var cameraName = this._cameras[i].name;
  66145. if (this._renderEffectsForIsolatedPass[cameraName]) {
  66146. this._renderEffectsForIsolatedPass[cameraName]._update();
  66147. }
  66148. }
  66149. };
  66150. PostProcessRenderPipeline.prototype._reset = function () {
  66151. this._renderEffects = {};
  66152. this._renderEffectsForIsolatedPass = new Array();
  66153. };
  66154. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  66155. // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
  66156. var effectKeys = Object.keys(this._renderEffects);
  66157. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  66158. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  66159. if (postProcesses) {
  66160. postProcesses[0].samples = 4;
  66161. return true;
  66162. }
  66163. }
  66164. return false;
  66165. };
  66166. PostProcessRenderPipeline.prototype.dispose = function () {
  66167. // Must be implemented by children
  66168. };
  66169. __decorate([
  66170. BABYLON.serialize()
  66171. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  66172. return PostProcessRenderPipeline;
  66173. }());
  66174. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  66175. })(BABYLON || (BABYLON = {}));
  66176. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  66177. var BABYLON;
  66178. (function (BABYLON) {
  66179. /**
  66180. * This represents a depth renderer in Babylon.
  66181. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  66182. */
  66183. var DepthRenderer = /** @class */ (function () {
  66184. /**
  66185. * Instantiates a depth renderer
  66186. * @param scene The scene the renderer belongs to
  66187. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  66188. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  66189. */
  66190. function DepthRenderer(scene, type, camera) {
  66191. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66192. if (camera === void 0) { camera = null; }
  66193. var _this = this;
  66194. this._scene = scene;
  66195. this._camera = camera;
  66196. var engine = scene.getEngine();
  66197. // Render target
  66198. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  66199. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66200. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66201. this._depthMap.refreshRate = 1;
  66202. this._depthMap.renderParticles = false;
  66203. this._depthMap.renderList = null;
  66204. // Camera to get depth map from to support multiple concurrent cameras
  66205. this._depthMap.activeCamera = this._camera;
  66206. this._depthMap.ignoreCameraViewport = true;
  66207. this._depthMap.useCameraPostProcesses = false;
  66208. // set default depth value to 1.0 (far away)
  66209. this._depthMap.onClearObservable.add(function (engine) {
  66210. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  66211. });
  66212. // Custom render function
  66213. var renderSubMesh = function (subMesh) {
  66214. var mesh = subMesh.getRenderingMesh();
  66215. var scene = _this._scene;
  66216. var engine = scene.getEngine();
  66217. var material = subMesh.getMaterial();
  66218. if (!material) {
  66219. return;
  66220. }
  66221. // Culling and reverse (right handed system)
  66222. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  66223. // Managing instances
  66224. var batch = mesh._getInstancesRenderList(subMesh._id);
  66225. if (batch.mustReturn) {
  66226. return;
  66227. }
  66228. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  66229. var camera = _this._camera || scene.activeCamera;
  66230. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  66231. engine.enableEffect(_this._effect);
  66232. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  66233. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  66234. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  66235. // Alpha test
  66236. if (material && material.needAlphaTesting()) {
  66237. var alphaTexture = material.getAlphaTestTexture();
  66238. if (alphaTexture) {
  66239. _this._effect.setTexture("diffuseSampler", alphaTexture);
  66240. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  66241. }
  66242. }
  66243. // Bones
  66244. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  66245. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  66246. }
  66247. // Draw
  66248. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66249. }
  66250. };
  66251. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66252. var index;
  66253. if (depthOnlySubMeshes.length) {
  66254. engine.setColorWrite(false);
  66255. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66256. renderSubMesh(depthOnlySubMeshes.data[index]);
  66257. }
  66258. engine.setColorWrite(true);
  66259. }
  66260. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66261. renderSubMesh(opaqueSubMeshes.data[index]);
  66262. }
  66263. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66264. renderSubMesh(alphaTestSubMeshes.data[index]);
  66265. }
  66266. };
  66267. }
  66268. /**
  66269. * Creates the depth rendering effect and checks if the effect is ready.
  66270. * @param subMesh The submesh to be used to render the depth map of
  66271. * @param useInstances If multiple world instances should be used
  66272. * @returns if the depth renderer is ready to render the depth map
  66273. */
  66274. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  66275. var material = subMesh.getMaterial();
  66276. if (material.disableDepthWrite) {
  66277. return false;
  66278. }
  66279. var defines = [];
  66280. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66281. var mesh = subMesh.getMesh();
  66282. // Alpha test
  66283. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  66284. defines.push("#define ALPHATEST");
  66285. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66286. attribs.push(BABYLON.VertexBuffer.UVKind);
  66287. defines.push("#define UV1");
  66288. }
  66289. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66290. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66291. defines.push("#define UV2");
  66292. }
  66293. }
  66294. // Bones
  66295. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66296. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66297. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66298. if (mesh.numBoneInfluencers > 4) {
  66299. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66300. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66301. }
  66302. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66303. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66304. }
  66305. else {
  66306. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66307. }
  66308. // Instances
  66309. if (useInstances) {
  66310. defines.push("#define INSTANCES");
  66311. attribs.push("world0");
  66312. attribs.push("world1");
  66313. attribs.push("world2");
  66314. attribs.push("world3");
  66315. }
  66316. // Get correct effect
  66317. var join = defines.join("\n");
  66318. if (this._cachedDefines !== join) {
  66319. this._cachedDefines = join;
  66320. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  66321. }
  66322. return this._effect.isReady();
  66323. };
  66324. /**
  66325. * Gets the texture which the depth map will be written to.
  66326. * @returns The depth map texture
  66327. */
  66328. DepthRenderer.prototype.getDepthMap = function () {
  66329. return this._depthMap;
  66330. };
  66331. /**
  66332. * Disposes of the depth renderer.
  66333. */
  66334. DepthRenderer.prototype.dispose = function () {
  66335. this._depthMap.dispose();
  66336. };
  66337. return DepthRenderer;
  66338. }());
  66339. BABYLON.DepthRenderer = DepthRenderer;
  66340. })(BABYLON || (BABYLON = {}));
  66341. //# sourceMappingURL=babylon.depthRenderer.js.map
  66342. var BABYLON;
  66343. (function (BABYLON) {
  66344. var SSAORenderingPipeline = /** @class */ (function (_super) {
  66345. __extends(SSAORenderingPipeline, _super);
  66346. /**
  66347. * @constructor
  66348. * @param {string} name - The rendering pipeline name
  66349. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66350. * @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 }
  66351. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66352. */
  66353. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  66354. var _this = _super.call(this, scene.getEngine(), name) || this;
  66355. // Members
  66356. /**
  66357. * The PassPostProcess id in the pipeline that contains the original scene color
  66358. * @type {string}
  66359. */
  66360. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66361. /**
  66362. * The SSAO PostProcess id in the pipeline
  66363. * @type {string}
  66364. */
  66365. _this.SSAORenderEffect = "SSAORenderEffect";
  66366. /**
  66367. * The horizontal blur PostProcess id in the pipeline
  66368. * @type {string}
  66369. */
  66370. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66371. /**
  66372. * The vertical blur PostProcess id in the pipeline
  66373. * @type {string}
  66374. */
  66375. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66376. /**
  66377. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66378. * @type {string}
  66379. */
  66380. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66381. /**
  66382. * The output strength of the SSAO post-process. Default value is 1.0.
  66383. * @type {number}
  66384. */
  66385. _this.totalStrength = 1.0;
  66386. /**
  66387. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  66388. * @type {number}
  66389. */
  66390. _this.radius = 0.0001;
  66391. /**
  66392. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  66393. * Must not be equal to fallOff and superior to fallOff.
  66394. * Default value is 0.975
  66395. * @type {number}
  66396. */
  66397. _this.area = 0.0075;
  66398. /**
  66399. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  66400. * Must not be equal to area and inferior to area.
  66401. * Default value is 0.0
  66402. * @type {number}
  66403. */
  66404. _this.fallOff = 0.000001;
  66405. /**
  66406. * The base color of the SSAO post-process
  66407. * The final result is "base + ssao" between [0, 1]
  66408. * @type {number}
  66409. */
  66410. _this.base = 0.5;
  66411. _this._firstUpdate = true;
  66412. _this._scene = scene;
  66413. // Set up assets
  66414. _this._createRandomTexture();
  66415. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66416. var ssaoRatio = ratio.ssaoRatio || ratio;
  66417. var combineRatio = ratio.combineRatio || ratio;
  66418. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66419. _this._createSSAOPostProcess(ssaoRatio);
  66420. _this._createBlurPostProcess(ssaoRatio);
  66421. _this._createSSAOCombinePostProcess(combineRatio);
  66422. // Set up pipeline
  66423. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66424. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66425. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66426. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66427. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66428. // Finish
  66429. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66430. if (cameras)
  66431. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66432. return _this;
  66433. }
  66434. // Public Methods
  66435. /**
  66436. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66437. */
  66438. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66439. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66440. for (var i = 0; i < this._scene.cameras.length; i++) {
  66441. var camera = this._scene.cameras[i];
  66442. this._originalColorPostProcess.dispose(camera);
  66443. this._ssaoPostProcess.dispose(camera);
  66444. this._blurHPostProcess.dispose(camera);
  66445. this._blurVPostProcess.dispose(camera);
  66446. this._ssaoCombinePostProcess.dispose(camera);
  66447. }
  66448. this._randomTexture.dispose();
  66449. if (disableDepthRender)
  66450. this._scene.disableDepthRenderer();
  66451. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66452. _super.prototype.dispose.call(this);
  66453. };
  66454. // Private Methods
  66455. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  66456. var _this = this;
  66457. var size = 16;
  66458. 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);
  66459. 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);
  66460. this._blurHPostProcess.onActivateObservable.add(function () {
  66461. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  66462. _this._blurHPostProcess.kernel = size * dw;
  66463. });
  66464. this._blurVPostProcess.onActivateObservable.add(function () {
  66465. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  66466. _this._blurVPostProcess.kernel = size * dw;
  66467. });
  66468. };
  66469. SSAORenderingPipeline.prototype._rebuild = function () {
  66470. this._firstUpdate = true;
  66471. _super.prototype._rebuild.call(this);
  66472. };
  66473. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66474. var _this = this;
  66475. var numSamples = 16;
  66476. var sampleSphere = [
  66477. 0.5381, 0.1856, -0.4319,
  66478. 0.1379, 0.2486, 0.4430,
  66479. 0.3371, 0.5679, -0.0057,
  66480. -0.6999, -0.0451, -0.0019,
  66481. 0.0689, -0.1598, -0.8547,
  66482. 0.0560, 0.0069, -0.1843,
  66483. -0.0146, 0.1402, 0.0762,
  66484. 0.0100, -0.1924, -0.0344,
  66485. -0.3577, -0.5301, -0.4358,
  66486. -0.3169, 0.1063, 0.0158,
  66487. 0.0103, -0.5869, 0.0046,
  66488. -0.0897, -0.4940, 0.3287,
  66489. 0.7119, -0.0154, -0.0918,
  66490. -0.0533, 0.0596, -0.5411,
  66491. 0.0352, -0.0631, 0.5460,
  66492. -0.4776, 0.2847, -0.0271
  66493. ];
  66494. var samplesFactor = 1.0 / numSamples;
  66495. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  66496. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66497. "area", "fallOff", "base", "range", "viewport"
  66498. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66499. this._ssaoPostProcess.onApply = function (effect) {
  66500. if (_this._firstUpdate) {
  66501. effect.setArray3("sampleSphere", sampleSphere);
  66502. effect.setFloat("samplesFactor", samplesFactor);
  66503. effect.setFloat("randTextureTiles", 4.0);
  66504. }
  66505. effect.setFloat("totalStrength", _this.totalStrength);
  66506. effect.setFloat("radius", _this.radius);
  66507. effect.setFloat("area", _this.area);
  66508. effect.setFloat("fallOff", _this.fallOff);
  66509. effect.setFloat("base", _this.base);
  66510. effect.setTexture("textureSampler", _this._depthTexture);
  66511. effect.setTexture("randomSampler", _this._randomTexture);
  66512. };
  66513. };
  66514. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66515. var _this = this;
  66516. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66517. this._ssaoCombinePostProcess.onApply = function (effect) {
  66518. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66519. };
  66520. };
  66521. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  66522. var size = 512;
  66523. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66524. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66525. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66526. var context = this._randomTexture.getContext();
  66527. var rand = function (min, max) {
  66528. return Math.random() * (max - min) + min;
  66529. };
  66530. var randVector = BABYLON.Vector3.Zero();
  66531. for (var x = 0; x < size; x++) {
  66532. for (var y = 0; y < size; y++) {
  66533. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  66534. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  66535. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  66536. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66537. context.fillRect(x, y, 1, 1);
  66538. }
  66539. }
  66540. this._randomTexture.update(false);
  66541. };
  66542. __decorate([
  66543. BABYLON.serialize()
  66544. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  66545. __decorate([
  66546. BABYLON.serialize()
  66547. ], SSAORenderingPipeline.prototype, "radius", void 0);
  66548. __decorate([
  66549. BABYLON.serialize()
  66550. ], SSAORenderingPipeline.prototype, "area", void 0);
  66551. __decorate([
  66552. BABYLON.serialize()
  66553. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  66554. __decorate([
  66555. BABYLON.serialize()
  66556. ], SSAORenderingPipeline.prototype, "base", void 0);
  66557. return SSAORenderingPipeline;
  66558. }(BABYLON.PostProcessRenderPipeline));
  66559. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  66560. })(BABYLON || (BABYLON = {}));
  66561. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  66562. var BABYLON;
  66563. (function (BABYLON) {
  66564. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  66565. __extends(SSAO2RenderingPipeline, _super);
  66566. /**
  66567. * @constructor
  66568. * @param {string} name - The rendering pipeline name
  66569. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66570. * @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 }
  66571. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66572. */
  66573. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  66574. var _this = _super.call(this, scene.getEngine(), name) || this;
  66575. // Members
  66576. /**
  66577. * The PassPostProcess id in the pipeline that contains the original scene color
  66578. * @type {string}
  66579. */
  66580. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66581. /**
  66582. * The SSAO PostProcess id in the pipeline
  66583. * @type {string}
  66584. */
  66585. _this.SSAORenderEffect = "SSAORenderEffect";
  66586. /**
  66587. * The horizontal blur PostProcess id in the pipeline
  66588. * @type {string}
  66589. */
  66590. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66591. /**
  66592. * The vertical blur PostProcess id in the pipeline
  66593. * @type {string}
  66594. */
  66595. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66596. /**
  66597. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66598. * @type {string}
  66599. */
  66600. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66601. /**
  66602. * The output strength of the SSAO post-process. Default value is 1.0.
  66603. * @type {number}
  66604. */
  66605. _this.totalStrength = 1.0;
  66606. /**
  66607. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  66608. * @type {number}
  66609. */
  66610. _this.maxZ = 100.0;
  66611. /**
  66612. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  66613. * @type {number}
  66614. */
  66615. _this.minZAspect = 0.2;
  66616. /**
  66617. * Number of samples used for the SSAO calculations. Default value is 8
  66618. * @type {number}
  66619. */
  66620. _this._samples = 8;
  66621. /**
  66622. * Are we using bilateral blur ?
  66623. * @type {boolean}
  66624. */
  66625. _this._expensiveBlur = true;
  66626. /**
  66627. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  66628. * @type {number}
  66629. */
  66630. _this.radius = 2.0;
  66631. /**
  66632. * The base color of the SSAO post-process
  66633. * The final result is "base + ssao" between [0, 1]
  66634. * @type {number}
  66635. */
  66636. _this.base = 0.1;
  66637. _this._firstUpdate = true;
  66638. _this._scene = scene;
  66639. if (!_this.isSupported) {
  66640. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  66641. return _this;
  66642. }
  66643. var ssaoRatio = ratio.ssaoRatio || ratio;
  66644. var blurRatio = ratio.blurRatio || ratio;
  66645. // Set up assets
  66646. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  66647. _this._createRandomTexture();
  66648. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  66649. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  66650. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66651. _this._createSSAOPostProcess(1.0);
  66652. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  66653. _this._createSSAOCombinePostProcess(blurRatio);
  66654. // Set up pipeline
  66655. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66656. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66657. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66658. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66659. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66660. // Finish
  66661. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66662. if (cameras)
  66663. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66664. return _this;
  66665. }
  66666. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  66667. get: function () {
  66668. return this._samples;
  66669. },
  66670. set: function (n) {
  66671. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  66672. this._samples = n;
  66673. this._sampleSphere = this._generateHemisphere();
  66674. this._firstUpdate = true;
  66675. },
  66676. enumerable: true,
  66677. configurable: true
  66678. });
  66679. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  66680. get: function () {
  66681. return this._expensiveBlur;
  66682. },
  66683. set: function (b) {
  66684. 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"]);
  66685. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  66686. this._expensiveBlur = b;
  66687. this._firstUpdate = true;
  66688. },
  66689. enumerable: true,
  66690. configurable: true
  66691. });
  66692. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  66693. /**
  66694. * Support test.
  66695. * @type {boolean}
  66696. */
  66697. get: function () {
  66698. var engine = BABYLON.Engine.LastCreatedEngine;
  66699. if (!engine) {
  66700. return false;
  66701. }
  66702. return engine.getCaps().drawBuffersExtension;
  66703. },
  66704. enumerable: true,
  66705. configurable: true
  66706. });
  66707. // Public Methods
  66708. /**
  66709. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66710. */
  66711. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  66712. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  66713. for (var i = 0; i < this._scene.cameras.length; i++) {
  66714. var camera = this._scene.cameras[i];
  66715. this._originalColorPostProcess.dispose(camera);
  66716. this._ssaoPostProcess.dispose(camera);
  66717. this._blurHPostProcess.dispose(camera);
  66718. this._blurVPostProcess.dispose(camera);
  66719. this._ssaoCombinePostProcess.dispose(camera);
  66720. }
  66721. this._randomTexture.dispose();
  66722. if (disableGeometryBufferRenderer)
  66723. this._scene.disableGeometryBufferRenderer();
  66724. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66725. _super.prototype.dispose.call(this);
  66726. };
  66727. // Private Methods
  66728. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  66729. var _this = this;
  66730. this._samplerOffsets = [];
  66731. var expensive = this.expensiveBlur;
  66732. for (var i = -8; i < 8; i++) {
  66733. this._samplerOffsets.push(i * 2 + 0.5);
  66734. }
  66735. 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");
  66736. this._blurHPostProcess.onApply = function (effect) {
  66737. if (!_this._scene.activeCamera) {
  66738. return;
  66739. }
  66740. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  66741. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66742. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66743. effect.setFloat("radius", _this.radius);
  66744. effect.setTexture("depthSampler", _this._depthTexture);
  66745. if (_this._firstUpdate) {
  66746. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66747. }
  66748. };
  66749. 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");
  66750. this._blurVPostProcess.onApply = function (effect) {
  66751. if (!_this._scene.activeCamera) {
  66752. return;
  66753. }
  66754. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  66755. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66756. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66757. effect.setFloat("radius", _this.radius);
  66758. effect.setTexture("depthSampler", _this._depthTexture);
  66759. if (_this._firstUpdate) {
  66760. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66761. _this._firstUpdate = false;
  66762. }
  66763. };
  66764. };
  66765. SSAO2RenderingPipeline.prototype._rebuild = function () {
  66766. this._firstUpdate = true;
  66767. _super.prototype._rebuild.call(this);
  66768. };
  66769. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  66770. var numSamples = this.samples;
  66771. var result = [];
  66772. var vector, scale;
  66773. var rand = function (min, max) {
  66774. return Math.random() * (max - min) + min;
  66775. };
  66776. var i = 0;
  66777. while (i < numSamples) {
  66778. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  66779. vector.normalize();
  66780. scale = i / numSamples;
  66781. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  66782. vector.scaleInPlace(scale);
  66783. result.push(vector.x, vector.y, vector.z);
  66784. i++;
  66785. }
  66786. return result;
  66787. };
  66788. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66789. var _this = this;
  66790. var numSamples = this.samples;
  66791. this._sampleSphere = this._generateHemisphere();
  66792. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  66793. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66794. "base", "range", "projection", "near", "far", "texelSize",
  66795. "xViewport", "yViewport", "maxZ", "minZAspect"
  66796. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66797. this._ssaoPostProcess.onApply = function (effect) {
  66798. if (_this._firstUpdate) {
  66799. effect.setArray3("sampleSphere", _this._sampleSphere);
  66800. effect.setFloat("randTextureTiles", 4.0);
  66801. }
  66802. if (!_this._scene.activeCamera) {
  66803. return;
  66804. }
  66805. effect.setFloat("samplesFactor", 1 / _this.samples);
  66806. effect.setFloat("totalStrength", _this.totalStrength);
  66807. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  66808. effect.setFloat("radius", _this.radius);
  66809. effect.setFloat("maxZ", _this.maxZ);
  66810. effect.setFloat("minZAspect", _this.minZAspect);
  66811. effect.setFloat("base", _this.base);
  66812. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66813. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66814. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  66815. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  66816. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  66817. effect.setTexture("textureSampler", _this._depthTexture);
  66818. effect.setTexture("normalSampler", _this._normalTexture);
  66819. effect.setTexture("randomSampler", _this._randomTexture);
  66820. };
  66821. };
  66822. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66823. var _this = this;
  66824. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66825. this._ssaoCombinePostProcess.onApply = function (effect) {
  66826. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66827. };
  66828. };
  66829. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  66830. var size = 512;
  66831. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66832. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66833. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66834. var context = this._randomTexture.getContext();
  66835. var rand = function (min, max) {
  66836. return Math.random() * (max - min) + min;
  66837. };
  66838. var randVector = BABYLON.Vector3.Zero();
  66839. for (var x = 0; x < size; x++) {
  66840. for (var y = 0; y < size; y++) {
  66841. randVector.x = rand(0.0, 1.0);
  66842. randVector.y = rand(0.0, 1.0);
  66843. randVector.z = 0.0;
  66844. randVector.normalize();
  66845. randVector.scaleInPlace(255);
  66846. randVector.x = Math.floor(randVector.x);
  66847. randVector.y = Math.floor(randVector.y);
  66848. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66849. context.fillRect(x, y, 1, 1);
  66850. }
  66851. }
  66852. this._randomTexture.update(false);
  66853. };
  66854. __decorate([
  66855. BABYLON.serialize()
  66856. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  66857. __decorate([
  66858. BABYLON.serialize()
  66859. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  66860. __decorate([
  66861. BABYLON.serialize()
  66862. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  66863. __decorate([
  66864. BABYLON.serialize("samples")
  66865. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  66866. __decorate([
  66867. BABYLON.serialize("expensiveBlur")
  66868. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  66869. __decorate([
  66870. BABYLON.serialize()
  66871. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  66872. __decorate([
  66873. BABYLON.serialize()
  66874. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  66875. return SSAO2RenderingPipeline;
  66876. }(BABYLON.PostProcessRenderPipeline));
  66877. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  66878. })(BABYLON || (BABYLON = {}));
  66879. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  66880. // BABYLON.JS Chromatic Aberration GLSL Shader
  66881. // Author: Olivier Guyot
  66882. // Separates very slightly R, G and B colors on the edges of the screen
  66883. // Inspired by Francois Tarlier & Martins Upitis
  66884. var BABYLON;
  66885. (function (BABYLON) {
  66886. var LensRenderingPipeline = /** @class */ (function (_super) {
  66887. __extends(LensRenderingPipeline, _super);
  66888. /**
  66889. * @constructor
  66890. *
  66891. * Effect parameters are as follow:
  66892. * {
  66893. * chromatic_aberration: number; // from 0 to x (1 for realism)
  66894. * edge_blur: number; // from 0 to x (1 for realism)
  66895. * distortion: number; // from 0 to x (1 for realism)
  66896. * grain_amount: number; // from 0 to 1
  66897. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  66898. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  66899. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  66900. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  66901. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  66902. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  66903. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  66904. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  66905. * }
  66906. * Note: if an effect parameter is unset, effect is disabled
  66907. *
  66908. * @param {string} name - The rendering pipeline name
  66909. * @param {object} parameters - An object containing all parameters (see above)
  66910. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66911. * @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)
  66912. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66913. */
  66914. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  66915. if (ratio === void 0) { ratio = 1.0; }
  66916. var _this = _super.call(this, scene.getEngine(), name) || this;
  66917. // Lens effects can be of the following:
  66918. // - chromatic aberration (slight shift of RGB colors)
  66919. // - blur on the edge of the lens
  66920. // - lens distortion
  66921. // - depth-of-field blur & highlights enhancing
  66922. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  66923. // - grain effect (noise or custom texture)
  66924. // Two additional texture samplers are needed:
  66925. // - depth map (for depth-of-field)
  66926. // - grain texture
  66927. /**
  66928. * The chromatic aberration PostProcess id in the pipeline
  66929. * @type {string}
  66930. */
  66931. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  66932. /**
  66933. * The highlights enhancing PostProcess id in the pipeline
  66934. * @type {string}
  66935. */
  66936. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  66937. /**
  66938. * The depth-of-field PostProcess id in the pipeline
  66939. * @type {string}
  66940. */
  66941. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  66942. _this._scene = scene;
  66943. // Fetch texture samplers
  66944. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66945. if (parameters.grain_texture) {
  66946. _this._grainTexture = parameters.grain_texture;
  66947. }
  66948. else {
  66949. _this._createGrainTexture();
  66950. }
  66951. // save parameters
  66952. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  66953. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  66954. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  66955. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  66956. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  66957. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  66958. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  66959. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  66960. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  66961. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  66962. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  66963. // Create effects
  66964. _this._createChromaticAberrationPostProcess(ratio);
  66965. _this._createHighlightsPostProcess(ratio);
  66966. _this._createDepthOfFieldPostProcess(ratio / 4);
  66967. // Set up pipeline
  66968. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  66969. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  66970. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  66971. if (_this._highlightsGain === -1) {
  66972. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  66973. }
  66974. // Finish
  66975. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66976. if (cameras) {
  66977. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66978. }
  66979. return _this;
  66980. }
  66981. // public methods (self explanatory)
  66982. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  66983. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  66984. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  66985. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  66986. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  66987. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  66988. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  66989. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  66990. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  66991. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  66992. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  66993. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  66994. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  66995. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  66996. };
  66997. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  66998. this._highlightsPostProcess.updateEffect();
  66999. };
  67000. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  67001. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  67002. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  67003. this._highlightsGain = amount;
  67004. };
  67005. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  67006. if (this._highlightsGain === -1) {
  67007. this._highlightsGain = 1.0;
  67008. }
  67009. this._highlightsThreshold = amount;
  67010. };
  67011. LensRenderingPipeline.prototype.disableHighlights = function () {
  67012. this._highlightsGain = -1;
  67013. };
  67014. /**
  67015. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  67016. */
  67017. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67018. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67019. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67020. this._chromaticAberrationPostProcess = null;
  67021. this._highlightsPostProcess = null;
  67022. this._depthOfFieldPostProcess = null;
  67023. this._grainTexture.dispose();
  67024. if (disableDepthRender)
  67025. this._scene.disableDepthRenderer();
  67026. };
  67027. // colors shifting and distortion
  67028. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  67029. var _this = this;
  67030. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  67031. [], // samplers
  67032. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67033. this._chromaticAberrationPostProcess.onApply = function (effect) {
  67034. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  67035. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67036. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67037. effect.setFloat('radialIntensity', 1);
  67038. effect.setFloat2('direction', 17, 17);
  67039. effect.setFloat2('centerPosition', 0.5, 0.5);
  67040. };
  67041. };
  67042. // highlights enhancing
  67043. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  67044. var _this = this;
  67045. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  67046. [], // samplers
  67047. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  67048. this._highlightsPostProcess.onApply = function (effect) {
  67049. effect.setFloat('gain', _this._highlightsGain);
  67050. effect.setFloat('threshold', _this._highlightsThreshold);
  67051. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  67052. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67053. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67054. };
  67055. };
  67056. // colors shifting and distortion
  67057. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  67058. var _this = this;
  67059. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  67060. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  67061. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  67062. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67063. this._depthOfFieldPostProcess.onApply = function (effect) {
  67064. effect.setTexture("depthSampler", _this._depthTexture);
  67065. effect.setTexture("grainSampler", _this._grainTexture);
  67066. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  67067. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  67068. effect.setFloat('grain_amount', _this._grainAmount);
  67069. effect.setBool('blur_noise', _this._blurNoise);
  67070. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67071. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67072. effect.setFloat('distortion', _this._distortion);
  67073. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  67074. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  67075. effect.setFloat('aperture', _this._dofAperture);
  67076. effect.setFloat('darken', _this._dofDarken);
  67077. effect.setFloat('edge_blur', _this._edgeBlur);
  67078. effect.setBool('highlights', (_this._highlightsGain !== -1));
  67079. if (_this._scene.activeCamera) {
  67080. effect.setFloat('near', _this._scene.activeCamera.minZ);
  67081. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  67082. }
  67083. };
  67084. };
  67085. // creates a black and white random noise texture, 512x512
  67086. LensRenderingPipeline.prototype._createGrainTexture = function () {
  67087. var size = 512;
  67088. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67089. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67090. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67091. var context = this._grainTexture.getContext();
  67092. var rand = function (min, max) {
  67093. return Math.random() * (max - min) + min;
  67094. };
  67095. var value;
  67096. for (var x = 0; x < size; x++) {
  67097. for (var y = 0; y < size; y++) {
  67098. value = Math.floor(rand(0.42, 0.58) * 255);
  67099. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  67100. context.fillRect(x, y, 1, 1);
  67101. }
  67102. }
  67103. this._grainTexture.update(false);
  67104. };
  67105. return LensRenderingPipeline;
  67106. }(BABYLON.PostProcessRenderPipeline));
  67107. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  67108. })(BABYLON || (BABYLON = {}));
  67109. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  67110. var BABYLON;
  67111. (function (BABYLON) {
  67112. var StandardRenderingPipeline = /** @class */ (function (_super) {
  67113. __extends(StandardRenderingPipeline, _super);
  67114. /**
  67115. * @constructor
  67116. * @param {string} name - The rendering pipeline name
  67117. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67118. * @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)
  67119. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  67120. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67121. */
  67122. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  67123. if (originalPostProcess === void 0) { originalPostProcess = null; }
  67124. var _this = _super.call(this, scene.getEngine(), name) || this;
  67125. _this.downSampleX4PostProcess = null;
  67126. _this.brightPassPostProcess = null;
  67127. _this.blurHPostProcesses = [];
  67128. _this.blurVPostProcesses = [];
  67129. _this.textureAdderPostProcess = null;
  67130. _this.volumetricLightPostProcess = null;
  67131. _this.volumetricLightSmoothXPostProcess = null;
  67132. _this.volumetricLightSmoothYPostProcess = null;
  67133. _this.volumetricLightMergePostProces = null;
  67134. _this.volumetricLightFinalPostProcess = null;
  67135. _this.luminancePostProcess = null;
  67136. _this.luminanceDownSamplePostProcesses = [];
  67137. _this.hdrPostProcess = null;
  67138. _this.textureAdderFinalPostProcess = null;
  67139. _this.lensFlareFinalPostProcess = null;
  67140. _this.hdrFinalPostProcess = null;
  67141. _this.lensFlarePostProcess = null;
  67142. _this.lensFlareComposePostProcess = null;
  67143. _this.motionBlurPostProcess = null;
  67144. _this.depthOfFieldPostProcess = null;
  67145. // Values
  67146. _this.brightThreshold = 1.0;
  67147. _this.blurWidth = 512.0;
  67148. _this.horizontalBlur = false;
  67149. _this.exposure = 1.0;
  67150. _this.lensTexture = null;
  67151. _this.volumetricLightCoefficient = 0.2;
  67152. _this.volumetricLightPower = 4.0;
  67153. _this.volumetricLightBlurScale = 64.0;
  67154. _this.sourceLight = null;
  67155. _this.hdrMinimumLuminance = 1.0;
  67156. _this.hdrDecreaseRate = 0.5;
  67157. _this.hdrIncreaseRate = 0.5;
  67158. _this.lensColorTexture = null;
  67159. _this.lensFlareStrength = 20.0;
  67160. _this.lensFlareGhostDispersal = 1.4;
  67161. _this.lensFlareHaloWidth = 0.7;
  67162. _this.lensFlareDistortionStrength = 16.0;
  67163. _this.lensStarTexture = null;
  67164. _this.lensFlareDirtTexture = null;
  67165. _this.depthOfFieldDistance = 10.0;
  67166. _this.depthOfFieldBlurWidth = 64.0;
  67167. _this.motionStrength = 1.0;
  67168. // IAnimatable
  67169. _this.animations = [];
  67170. _this._currentDepthOfFieldSource = null;
  67171. _this._hdrCurrentLuminance = 1.0;
  67172. // Getters and setters
  67173. _this._bloomEnabled = true;
  67174. _this._depthOfFieldEnabled = false;
  67175. _this._vlsEnabled = false;
  67176. _this._lensFlareEnabled = false;
  67177. _this._hdrEnabled = false;
  67178. _this._motionBlurEnabled = false;
  67179. _this._motionBlurSamples = 64.0;
  67180. _this._volumetricLightStepsCount = 50.0;
  67181. _this._cameras = cameras || [];
  67182. // Initialize
  67183. _this._scene = scene;
  67184. _this._basePostProcess = originalPostProcess;
  67185. _this._ratio = ratio;
  67186. // Misc
  67187. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67188. // Finish
  67189. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67190. _this._buildPipeline();
  67191. return _this;
  67192. }
  67193. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  67194. get: function () {
  67195. return this._bloomEnabled;
  67196. },
  67197. set: function (enabled) {
  67198. if (this._bloomEnabled === enabled) {
  67199. return;
  67200. }
  67201. this._bloomEnabled = enabled;
  67202. this._buildPipeline();
  67203. },
  67204. enumerable: true,
  67205. configurable: true
  67206. });
  67207. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  67208. get: function () {
  67209. return this._depthOfFieldEnabled;
  67210. },
  67211. set: function (enabled) {
  67212. if (this._depthOfFieldEnabled === enabled) {
  67213. return;
  67214. }
  67215. this._depthOfFieldEnabled = enabled;
  67216. this._buildPipeline();
  67217. },
  67218. enumerable: true,
  67219. configurable: true
  67220. });
  67221. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  67222. get: function () {
  67223. return this._lensFlareEnabled;
  67224. },
  67225. set: function (enabled) {
  67226. if (this._lensFlareEnabled === enabled) {
  67227. return;
  67228. }
  67229. this._lensFlareEnabled = enabled;
  67230. this._buildPipeline();
  67231. },
  67232. enumerable: true,
  67233. configurable: true
  67234. });
  67235. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  67236. get: function () {
  67237. return this._hdrEnabled;
  67238. },
  67239. set: function (enabled) {
  67240. if (this._hdrEnabled === enabled) {
  67241. return;
  67242. }
  67243. this._hdrEnabled = enabled;
  67244. this._buildPipeline();
  67245. },
  67246. enumerable: true,
  67247. configurable: true
  67248. });
  67249. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  67250. get: function () {
  67251. return this._vlsEnabled;
  67252. },
  67253. set: function (enabled) {
  67254. if (this._vlsEnabled === enabled) {
  67255. return;
  67256. }
  67257. if (enabled) {
  67258. var geometry = this._scene.enableGeometryBufferRenderer();
  67259. if (!geometry) {
  67260. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  67261. return;
  67262. }
  67263. }
  67264. this._vlsEnabled = enabled;
  67265. this._buildPipeline();
  67266. },
  67267. enumerable: true,
  67268. configurable: true
  67269. });
  67270. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  67271. get: function () {
  67272. return this._motionBlurEnabled;
  67273. },
  67274. set: function (enabled) {
  67275. if (this._motionBlurEnabled === enabled) {
  67276. return;
  67277. }
  67278. this._motionBlurEnabled = enabled;
  67279. this._buildPipeline();
  67280. },
  67281. enumerable: true,
  67282. configurable: true
  67283. });
  67284. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  67285. get: function () {
  67286. return this._volumetricLightStepsCount;
  67287. },
  67288. set: function (count) {
  67289. if (this.volumetricLightPostProcess) {
  67290. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  67291. }
  67292. this._volumetricLightStepsCount = count;
  67293. },
  67294. enumerable: true,
  67295. configurable: true
  67296. });
  67297. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  67298. get: function () {
  67299. return this._motionBlurSamples;
  67300. },
  67301. set: function (samples) {
  67302. if (this.motionBlurPostProcess) {
  67303. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  67304. }
  67305. this._motionBlurSamples = samples;
  67306. },
  67307. enumerable: true,
  67308. configurable: true
  67309. });
  67310. StandardRenderingPipeline.prototype._buildPipeline = function () {
  67311. var _this = this;
  67312. var ratio = this._ratio;
  67313. var scene = this._scene;
  67314. this._disposePostProcesses();
  67315. this._reset();
  67316. // Create pass post-process
  67317. if (!this._basePostProcess) {
  67318. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  67319. this.originalPostProcess.onApply = function (effect) {
  67320. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  67321. };
  67322. }
  67323. else {
  67324. this.originalPostProcess = this._basePostProcess;
  67325. }
  67326. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  67327. this._currentDepthOfFieldSource = this.originalPostProcess;
  67328. if (this._vlsEnabled) {
  67329. // Create volumetric light
  67330. this._createVolumetricLightPostProcess(scene, ratio);
  67331. // Create volumetric light final post-process
  67332. 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);
  67333. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  67334. }
  67335. if (this._bloomEnabled) {
  67336. // Create down sample X4 post-process
  67337. this._createDownSampleX4PostProcess(scene, ratio / 2);
  67338. // Create bright pass post-process
  67339. this._createBrightPassPostProcess(scene, ratio / 2);
  67340. // Create gaussian blur post-processes (down sampling blurs)
  67341. this._createBlurPostProcesses(scene, ratio / 4, 1);
  67342. // Create texture adder post-process
  67343. this._createTextureAdderPostProcess(scene, ratio);
  67344. // Create depth-of-field source post-process
  67345. 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);
  67346. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  67347. }
  67348. if (this._lensFlareEnabled) {
  67349. // Create lens flare post-process
  67350. this._createLensFlarePostProcess(scene, ratio);
  67351. // Create depth-of-field source post-process post lens-flare and disable it now
  67352. 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);
  67353. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  67354. }
  67355. if (this._hdrEnabled) {
  67356. // Create luminance
  67357. this._createLuminancePostProcesses(scene, this._floatTextureType);
  67358. // Create HDR
  67359. this._createHdrPostProcess(scene, ratio);
  67360. // Create depth-of-field source post-process post hdr and disable it now
  67361. 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);
  67362. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  67363. }
  67364. if (this._depthOfFieldEnabled) {
  67365. // Create gaussian blur used by depth-of-field
  67366. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  67367. // Create depth-of-field post-process
  67368. this._createDepthOfFieldPostProcess(scene, ratio);
  67369. }
  67370. if (this._motionBlurEnabled) {
  67371. // Create motion blur post-process
  67372. this._createMotionBlurPostProcess(scene, ratio);
  67373. }
  67374. if (this._cameras !== null) {
  67375. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67376. }
  67377. };
  67378. // Down Sample X4 Post-Processs
  67379. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  67380. var _this = this;
  67381. var downSampleX4Offsets = new Array(32);
  67382. 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);
  67383. this.downSampleX4PostProcess.onApply = function (effect) {
  67384. var id = 0;
  67385. var width = _this.downSampleX4PostProcess.width;
  67386. var height = _this.downSampleX4PostProcess.height;
  67387. for (var i = -2; i < 2; i++) {
  67388. for (var j = -2; j < 2; j++) {
  67389. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  67390. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  67391. id += 2;
  67392. }
  67393. }
  67394. effect.setArray2("dsOffsets", downSampleX4Offsets);
  67395. };
  67396. // Add to pipeline
  67397. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  67398. };
  67399. // Brightpass Post-Process
  67400. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  67401. var _this = this;
  67402. var brightOffsets = new Array(8);
  67403. 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);
  67404. this.brightPassPostProcess.onApply = function (effect) {
  67405. var sU = (1.0 / _this.brightPassPostProcess.width);
  67406. var sV = (1.0 / _this.brightPassPostProcess.height);
  67407. brightOffsets[0] = -0.5 * sU;
  67408. brightOffsets[1] = 0.5 * sV;
  67409. brightOffsets[2] = 0.5 * sU;
  67410. brightOffsets[3] = 0.5 * sV;
  67411. brightOffsets[4] = -0.5 * sU;
  67412. brightOffsets[5] = -0.5 * sV;
  67413. brightOffsets[6] = 0.5 * sU;
  67414. brightOffsets[7] = -0.5 * sV;
  67415. effect.setArray2("dsOffsets", brightOffsets);
  67416. effect.setFloat("brightThreshold", _this.brightThreshold);
  67417. };
  67418. // Add to pipeline
  67419. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  67420. };
  67421. // Create blur H&V post-processes
  67422. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  67423. var _this = this;
  67424. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  67425. var engine = scene.getEngine();
  67426. 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);
  67427. 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);
  67428. blurX.onActivateObservable.add(function () {
  67429. var dw = blurX.width / engine.getRenderWidth();
  67430. blurX.kernel = _this[blurWidthKey] * dw;
  67431. });
  67432. blurY.onActivateObservable.add(function () {
  67433. var dw = blurY.height / engine.getRenderHeight();
  67434. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  67435. });
  67436. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  67437. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  67438. this.blurHPostProcesses.push(blurX);
  67439. this.blurVPostProcesses.push(blurY);
  67440. };
  67441. // Create texture adder post-process
  67442. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  67443. var _this = this;
  67444. 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);
  67445. this.textureAdderPostProcess.onApply = function (effect) {
  67446. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  67447. effect.setTexture("lensSampler", _this.lensTexture);
  67448. effect.setFloat("exposure", _this.exposure);
  67449. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  67450. };
  67451. // Add to pipeline
  67452. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  67453. };
  67454. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  67455. var _this = this;
  67456. var geometryRenderer = scene.enableGeometryBufferRenderer();
  67457. geometryRenderer.enablePosition = true;
  67458. var geometry = geometryRenderer.getGBuffer();
  67459. // Base post-process
  67460. 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));
  67461. var depthValues = BABYLON.Vector2.Zero();
  67462. this.volumetricLightPostProcess.onApply = function (effect) {
  67463. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  67464. var generator = _this.sourceLight.getShadowGenerator();
  67465. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  67466. effect.setTexture("positionSampler", geometry.textures[2]);
  67467. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  67468. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  67469. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  67470. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  67471. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  67472. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  67473. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  67474. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  67475. effect.setVector2("depthValues", depthValues);
  67476. }
  67477. };
  67478. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  67479. // Smooth
  67480. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  67481. // Merge
  67482. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  67483. this.volumetricLightMergePostProces.onApply = function (effect) {
  67484. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  67485. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  67486. };
  67487. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  67488. };
  67489. // Create luminance
  67490. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  67491. var _this = this;
  67492. // Create luminance
  67493. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  67494. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  67495. var offsets = [];
  67496. this.luminancePostProcess.onApply = function (effect) {
  67497. var sU = (1.0 / _this.luminancePostProcess.width);
  67498. var sV = (1.0 / _this.luminancePostProcess.height);
  67499. offsets[0] = -0.5 * sU;
  67500. offsets[1] = 0.5 * sV;
  67501. offsets[2] = 0.5 * sU;
  67502. offsets[3] = 0.5 * sV;
  67503. offsets[4] = -0.5 * sU;
  67504. offsets[5] = -0.5 * sV;
  67505. offsets[6] = 0.5 * sU;
  67506. offsets[7] = -0.5 * sV;
  67507. effect.setArray2("lumOffsets", offsets);
  67508. };
  67509. // Add to pipeline
  67510. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  67511. // Create down sample luminance
  67512. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  67513. var size = Math.pow(3, i);
  67514. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  67515. if (i === 0) {
  67516. defines += "#define FINAL_DOWN_SAMPLER";
  67517. }
  67518. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  67519. this.luminanceDownSamplePostProcesses.push(postProcess);
  67520. }
  67521. // Create callbacks and add effects
  67522. var lastLuminance = this.luminancePostProcess;
  67523. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  67524. var downSampleOffsets = new Array(18);
  67525. pp.onApply = function (effect) {
  67526. if (!lastLuminance) {
  67527. return;
  67528. }
  67529. var id = 0;
  67530. for (var x = -1; x < 2; x++) {
  67531. for (var y = -1; y < 2; y++) {
  67532. downSampleOffsets[id] = x / lastLuminance.width;
  67533. downSampleOffsets[id + 1] = y / lastLuminance.height;
  67534. id += 2;
  67535. }
  67536. }
  67537. effect.setArray2("dsOffsets", downSampleOffsets);
  67538. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  67539. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67540. lastLuminance = _this.luminancePostProcess;
  67541. }
  67542. else {
  67543. lastLuminance = pp;
  67544. }
  67545. };
  67546. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67547. pp.onAfterRender = function (effect) {
  67548. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  67549. 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);
  67550. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  67551. };
  67552. }
  67553. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  67554. });
  67555. };
  67556. // Create HDR post-process
  67557. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  67558. var _this = this;
  67559. 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);
  67560. var outputLiminance = 1;
  67561. var time = 0;
  67562. var lastTime = 0;
  67563. this.hdrPostProcess.onApply = function (effect) {
  67564. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  67565. time += scene.getEngine().getDeltaTime();
  67566. if (outputLiminance < 0) {
  67567. outputLiminance = _this._hdrCurrentLuminance;
  67568. }
  67569. else {
  67570. var dt = (lastTime - time) / 1000.0;
  67571. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  67572. outputLiminance += _this.hdrDecreaseRate * dt;
  67573. }
  67574. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  67575. outputLiminance -= _this.hdrIncreaseRate * dt;
  67576. }
  67577. else {
  67578. outputLiminance = _this._hdrCurrentLuminance;
  67579. }
  67580. }
  67581. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  67582. effect.setFloat("averageLuminance", outputLiminance);
  67583. lastTime = time;
  67584. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  67585. };
  67586. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  67587. };
  67588. // Create lens flare post-process
  67589. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  67590. var _this = this;
  67591. 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);
  67592. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  67593. this._createBlurPostProcesses(scene, ratio / 4, 2);
  67594. 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);
  67595. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  67596. var resolution = new BABYLON.Vector2(0, 0);
  67597. // Lens flare
  67598. this.lensFlarePostProcess.onApply = function (effect) {
  67599. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  67600. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  67601. effect.setFloat("strength", _this.lensFlareStrength);
  67602. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  67603. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  67604. // Shift
  67605. resolution.x = _this.lensFlarePostProcess.width;
  67606. resolution.y = _this.lensFlarePostProcess.height;
  67607. effect.setVector2("resolution", resolution);
  67608. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  67609. };
  67610. // Compose
  67611. 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);
  67612. 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);
  67613. this.lensFlareComposePostProcess.onApply = function (effect) {
  67614. if (!_this._scene.activeCamera) {
  67615. return;
  67616. }
  67617. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67618. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  67619. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  67620. // Lens start rotation matrix
  67621. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  67622. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  67623. 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));
  67624. camRot *= 4.0;
  67625. 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);
  67626. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  67627. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  67628. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  67629. };
  67630. };
  67631. // Create depth-of-field post-process
  67632. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  67633. var _this = this;
  67634. 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);
  67635. this.depthOfFieldPostProcess.onApply = function (effect) {
  67636. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67637. effect.setTexture("depthSampler", _this._getDepthTexture());
  67638. effect.setFloat("distance", _this.depthOfFieldDistance);
  67639. };
  67640. // Add to pipeline
  67641. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  67642. };
  67643. // Create motion blur post-process
  67644. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  67645. var _this = this;
  67646. 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);
  67647. var motionScale = 0;
  67648. var prevViewProjection = BABYLON.Matrix.Identity();
  67649. var invViewProjection = BABYLON.Matrix.Identity();
  67650. var viewProjection = BABYLON.Matrix.Identity();
  67651. var screenSize = BABYLON.Vector2.Zero();
  67652. this.motionBlurPostProcess.onApply = function (effect) {
  67653. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  67654. viewProjection.invertToRef(invViewProjection);
  67655. effect.setMatrix("inverseViewProjection", invViewProjection);
  67656. effect.setMatrix("prevViewProjection", prevViewProjection);
  67657. prevViewProjection = viewProjection;
  67658. screenSize.x = _this.motionBlurPostProcess.width;
  67659. screenSize.y = _this.motionBlurPostProcess.height;
  67660. effect.setVector2("screenSize", screenSize);
  67661. motionScale = scene.getEngine().getFps() / 60.0;
  67662. effect.setFloat("motionScale", motionScale);
  67663. effect.setFloat("motionStrength", _this.motionStrength);
  67664. effect.setTexture("depthSampler", _this._getDepthTexture());
  67665. };
  67666. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  67667. };
  67668. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  67669. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  67670. var renderer = this._scene.enableGeometryBufferRenderer();
  67671. return renderer.getGBuffer().textures[0];
  67672. }
  67673. return this._scene.enableDepthRenderer().getDepthMap();
  67674. };
  67675. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  67676. for (var i = 0; i < this._cameras.length; i++) {
  67677. var camera = this._cameras[i];
  67678. if (this.originalPostProcess) {
  67679. this.originalPostProcess.dispose(camera);
  67680. }
  67681. if (this.downSampleX4PostProcess) {
  67682. this.downSampleX4PostProcess.dispose(camera);
  67683. }
  67684. if (this.brightPassPostProcess) {
  67685. this.brightPassPostProcess.dispose(camera);
  67686. }
  67687. if (this.textureAdderPostProcess) {
  67688. this.textureAdderPostProcess.dispose(camera);
  67689. }
  67690. if (this.textureAdderFinalPostProcess) {
  67691. this.textureAdderFinalPostProcess.dispose(camera);
  67692. }
  67693. if (this.volumetricLightPostProcess) {
  67694. this.volumetricLightPostProcess.dispose(camera);
  67695. }
  67696. if (this.volumetricLightSmoothXPostProcess) {
  67697. this.volumetricLightSmoothXPostProcess.dispose(camera);
  67698. }
  67699. if (this.volumetricLightSmoothYPostProcess) {
  67700. this.volumetricLightSmoothYPostProcess.dispose(camera);
  67701. }
  67702. if (this.volumetricLightMergePostProces) {
  67703. this.volumetricLightMergePostProces.dispose(camera);
  67704. }
  67705. if (this.volumetricLightFinalPostProcess) {
  67706. this.volumetricLightFinalPostProcess.dispose(camera);
  67707. }
  67708. if (this.lensFlarePostProcess) {
  67709. this.lensFlarePostProcess.dispose(camera);
  67710. }
  67711. if (this.lensFlareComposePostProcess) {
  67712. this.lensFlareComposePostProcess.dispose(camera);
  67713. }
  67714. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  67715. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  67716. }
  67717. if (this.luminancePostProcess) {
  67718. this.luminancePostProcess.dispose(camera);
  67719. }
  67720. if (this.hdrPostProcess) {
  67721. this.hdrPostProcess.dispose(camera);
  67722. }
  67723. if (this.hdrFinalPostProcess) {
  67724. this.hdrFinalPostProcess.dispose(camera);
  67725. }
  67726. if (this.depthOfFieldPostProcess) {
  67727. this.depthOfFieldPostProcess.dispose(camera);
  67728. }
  67729. if (this.motionBlurPostProcess) {
  67730. this.motionBlurPostProcess.dispose(camera);
  67731. }
  67732. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  67733. this.blurHPostProcesses[j].dispose(camera);
  67734. }
  67735. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  67736. this.blurVPostProcesses[j].dispose(camera);
  67737. }
  67738. }
  67739. this.originalPostProcess = null;
  67740. this.downSampleX4PostProcess = null;
  67741. this.brightPassPostProcess = null;
  67742. this.textureAdderPostProcess = null;
  67743. this.textureAdderFinalPostProcess = null;
  67744. this.volumetricLightPostProcess = null;
  67745. this.volumetricLightSmoothXPostProcess = null;
  67746. this.volumetricLightSmoothYPostProcess = null;
  67747. this.volumetricLightMergePostProces = null;
  67748. this.volumetricLightFinalPostProcess = null;
  67749. this.lensFlarePostProcess = null;
  67750. this.lensFlareComposePostProcess = null;
  67751. this.luminancePostProcess = null;
  67752. this.hdrPostProcess = null;
  67753. this.hdrFinalPostProcess = null;
  67754. this.depthOfFieldPostProcess = null;
  67755. this.motionBlurPostProcess = null;
  67756. this.luminanceDownSamplePostProcesses = [];
  67757. this.blurHPostProcesses = [];
  67758. this.blurVPostProcesses = [];
  67759. };
  67760. // Dispose
  67761. StandardRenderingPipeline.prototype.dispose = function () {
  67762. this._disposePostProcesses();
  67763. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67764. _super.prototype.dispose.call(this);
  67765. };
  67766. // Serialize rendering pipeline
  67767. StandardRenderingPipeline.prototype.serialize = function () {
  67768. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67769. serializationObject.customType = "StandardRenderingPipeline";
  67770. return serializationObject;
  67771. };
  67772. /**
  67773. * Static members
  67774. */
  67775. // Parse serialized pipeline
  67776. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67777. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  67778. };
  67779. // Luminance steps
  67780. StandardRenderingPipeline.LuminanceSteps = 6;
  67781. __decorate([
  67782. BABYLON.serialize()
  67783. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  67784. __decorate([
  67785. BABYLON.serialize()
  67786. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  67787. __decorate([
  67788. BABYLON.serialize()
  67789. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  67790. __decorate([
  67791. BABYLON.serialize()
  67792. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  67793. __decorate([
  67794. BABYLON.serializeAsTexture("lensTexture")
  67795. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  67796. __decorate([
  67797. BABYLON.serialize()
  67798. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  67799. __decorate([
  67800. BABYLON.serialize()
  67801. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  67802. __decorate([
  67803. BABYLON.serialize()
  67804. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  67805. __decorate([
  67806. BABYLON.serialize()
  67807. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  67808. __decorate([
  67809. BABYLON.serialize()
  67810. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  67811. __decorate([
  67812. BABYLON.serialize()
  67813. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  67814. __decorate([
  67815. BABYLON.serializeAsTexture("lensColorTexture")
  67816. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  67817. __decorate([
  67818. BABYLON.serialize()
  67819. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  67820. __decorate([
  67821. BABYLON.serialize()
  67822. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  67823. __decorate([
  67824. BABYLON.serialize()
  67825. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  67826. __decorate([
  67827. BABYLON.serialize()
  67828. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  67829. __decorate([
  67830. BABYLON.serializeAsTexture("lensStarTexture")
  67831. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  67832. __decorate([
  67833. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  67834. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  67835. __decorate([
  67836. BABYLON.serialize()
  67837. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  67838. __decorate([
  67839. BABYLON.serialize()
  67840. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  67841. __decorate([
  67842. BABYLON.serialize()
  67843. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  67844. __decorate([
  67845. BABYLON.serialize()
  67846. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  67847. __decorate([
  67848. BABYLON.serialize()
  67849. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  67850. __decorate([
  67851. BABYLON.serialize()
  67852. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  67853. __decorate([
  67854. BABYLON.serialize()
  67855. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  67856. __decorate([
  67857. BABYLON.serialize()
  67858. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  67859. __decorate([
  67860. BABYLON.serialize()
  67861. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  67862. __decorate([
  67863. BABYLON.serialize()
  67864. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  67865. __decorate([
  67866. BABYLON.serialize()
  67867. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  67868. __decorate([
  67869. BABYLON.serialize()
  67870. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  67871. return StandardRenderingPipeline;
  67872. }(BABYLON.PostProcessRenderPipeline));
  67873. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  67874. })(BABYLON || (BABYLON = {}));
  67875. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  67876. var BABYLON;
  67877. (function (BABYLON) {
  67878. var FxaaPostProcess = /** @class */ (function (_super) {
  67879. __extends(FxaaPostProcess, _super);
  67880. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67881. if (camera === void 0) { camera = null; }
  67882. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67883. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  67884. _this.onApplyObservable.add(function (effect) {
  67885. var texelSize = _this.texelSize;
  67886. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  67887. });
  67888. return _this;
  67889. }
  67890. return FxaaPostProcess;
  67891. }(BABYLON.PostProcess));
  67892. BABYLON.FxaaPostProcess = FxaaPostProcess;
  67893. })(BABYLON || (BABYLON = {}));
  67894. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  67895. var BABYLON;
  67896. (function (BABYLON) {
  67897. /**
  67898. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  67899. */
  67900. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  67901. __extends(ChromaticAberrationPostProcess, _super);
  67902. /**
  67903. * Creates a new instance of @see ChromaticAberrationPostProcess
  67904. * @param name The name of the effect.
  67905. * @param screenWidth The width of the screen to apply the effect on.
  67906. * @param screenHeight The height of the screen to apply the effect on.
  67907. * @param options The required width/height ratio to downsize to before computing the render pass.
  67908. * @param camera The camera to apply the render pass to.
  67909. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67910. * @param engine The engine which the post process will be applied. (default: current engine)
  67911. * @param reusable If the post process can be reused on the same frame. (default: false)
  67912. * @param textureType Type of textures used when performing the post process. (default: 0)
  67913. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  67914. */
  67915. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  67916. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67917. if (blockCompilation === void 0) { blockCompilation = false; }
  67918. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  67919. /**
  67920. * The amount of seperation of rgb channels (default: 30)
  67921. */
  67922. _this.aberrationAmount = 30;
  67923. /**
  67924. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  67925. */
  67926. _this.radialIntensity = 0;
  67927. /**
  67928. * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
  67929. */
  67930. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  67931. /**
  67932. * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
  67933. */
  67934. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  67935. _this.onApplyObservable.add(function (effect) {
  67936. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  67937. effect.setFloat('screen_width', screenWidth);
  67938. effect.setFloat('screen_height', screenHeight);
  67939. effect.setFloat('radialIntensity', _this.radialIntensity);
  67940. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  67941. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  67942. });
  67943. return _this;
  67944. }
  67945. return ChromaticAberrationPostProcess;
  67946. }(BABYLON.PostProcess));
  67947. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  67948. })(BABYLON || (BABYLON = {}));
  67949. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  67950. var BABYLON;
  67951. (function (BABYLON) {
  67952. /**
  67953. * The SharpenPostProcess applies a sharpen kernel to every pixel
  67954. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  67955. */
  67956. var SharpenPostProcess = /** @class */ (function (_super) {
  67957. __extends(SharpenPostProcess, _super);
  67958. /**
  67959. * Creates a new instance of @see ConvolutionPostProcess
  67960. * @param name The name of the effect.
  67961. * @param options The required width/height ratio to downsize to before computing the render pass.
  67962. * @param camera The camera to apply the render pass to.
  67963. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67964. * @param engine The engine which the post process will be applied. (default: current engine)
  67965. * @param reusable If the post process can be reused on the same frame. (default: false)
  67966. * @param textureType Type of textures used when performing the post process. (default: 0)
  67967. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  67968. */
  67969. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  67970. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67971. if (blockCompilation === void 0) { blockCompilation = false; }
  67972. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  67973. /**
  67974. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  67975. */
  67976. _this.colorAmount = 1.0;
  67977. /**
  67978. * How much sharpness should be applied (default: 0.3)
  67979. */
  67980. _this.edgeAmount = 0.3;
  67981. _this.onApply = function (effect) {
  67982. effect.setFloat2("screenSize", _this.width, _this.height);
  67983. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  67984. };
  67985. return _this;
  67986. }
  67987. return SharpenPostProcess;
  67988. }(BABYLON.PostProcess));
  67989. BABYLON.SharpenPostProcess = SharpenPostProcess;
  67990. })(BABYLON || (BABYLON = {}));
  67991. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  67992. var BABYLON;
  67993. (function (BABYLON) {
  67994. /**
  67995. * The Blur Post Process which blurs an image based on a kernel and direction.
  67996. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  67997. */
  67998. var BlurPostProcess = /** @class */ (function (_super) {
  67999. __extends(BlurPostProcess, _super);
  68000. /**
  68001. * Creates a new instance of @see BlurPostProcess
  68002. * @param name The name of the effect.
  68003. * @param direction The direction in which to blur the image.
  68004. * @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.
  68005. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68006. * @param camera The camera to apply the render pass to.
  68007. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68008. * @param engine The engine which the post process will be applied. (default: current engine)
  68009. * @param reusable If the post process can be reused on the same frame. (default: false)
  68010. * @param textureType Type of textures used when performing the post process. (default: 0)
  68011. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68012. */
  68013. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  68014. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68015. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68016. if (defines === void 0) { defines = ""; }
  68017. if (blockCompilation === void 0) { blockCompilation = false; }
  68018. 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;
  68019. _this.direction = direction;
  68020. _this.blockCompilation = blockCompilation;
  68021. _this._packedFloat = false;
  68022. _this._staticDefines = "";
  68023. _this._staticDefines = defines;
  68024. _this.onApplyObservable.add(function (effect) {
  68025. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68026. });
  68027. _this.kernel = kernel;
  68028. return _this;
  68029. }
  68030. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68031. /**
  68032. * Gets the length in pixels of the blur sample region
  68033. */
  68034. get: function () {
  68035. return this._idealKernel;
  68036. },
  68037. /**
  68038. * Sets the length in pixels of the blur sample region
  68039. */
  68040. set: function (v) {
  68041. if (this._idealKernel === v) {
  68042. return;
  68043. }
  68044. v = Math.max(v, 1);
  68045. this._idealKernel = v;
  68046. this._kernel = this._nearestBestKernel(v);
  68047. if (!this.blockCompilation) {
  68048. this._updateParameters();
  68049. }
  68050. },
  68051. enumerable: true,
  68052. configurable: true
  68053. });
  68054. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68055. /**
  68056. * Gets wether or not the blur is unpacking/repacking floats
  68057. */
  68058. get: function () {
  68059. return this._packedFloat;
  68060. },
  68061. /**
  68062. * Sets wether or not the blur needs to unpack/repack floats
  68063. */
  68064. set: function (v) {
  68065. if (this._packedFloat === v) {
  68066. return;
  68067. }
  68068. this._packedFloat = v;
  68069. if (!this.blockCompilation) {
  68070. this._updateParameters();
  68071. }
  68072. },
  68073. enumerable: true,
  68074. configurable: true
  68075. });
  68076. /**
  68077. * Updates the effect with the current post process compile time values and recompiles the shader.
  68078. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68079. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68080. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68081. * @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
  68082. * @param onCompiled Called when the shader has been compiled.
  68083. * @param onError Called if there is an error when compiling a shader.
  68084. */
  68085. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68086. if (defines === void 0) { defines = null; }
  68087. if (uniforms === void 0) { uniforms = null; }
  68088. if (samplers === void 0) { samplers = null; }
  68089. this._updateParameters(onCompiled, onError);
  68090. };
  68091. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  68092. // Generate sampling offsets and weights
  68093. var N = this._kernel;
  68094. var centerIndex = (N - 1) / 2;
  68095. // Generate Gaussian sampling weights over kernel
  68096. var offsets = [];
  68097. var weights = [];
  68098. var totalWeight = 0;
  68099. for (var i = 0; i < N; i++) {
  68100. var u = i / (N - 1);
  68101. var w = this._gaussianWeight(u * 2.0 - 1);
  68102. offsets[i] = (i - centerIndex);
  68103. weights[i] = w;
  68104. totalWeight += w;
  68105. }
  68106. // Normalize weights
  68107. for (var i = 0; i < weights.length; i++) {
  68108. weights[i] /= totalWeight;
  68109. }
  68110. // Optimize: combine samples to take advantage of hardware linear sampling
  68111. // Walk from left to center, combining pairs (symmetrically)
  68112. var linearSamplingWeights = [];
  68113. var linearSamplingOffsets = [];
  68114. var linearSamplingMap = [];
  68115. for (var i = 0; i <= centerIndex; i += 2) {
  68116. var j = Math.min(i + 1, Math.floor(centerIndex));
  68117. var singleCenterSample = i === j;
  68118. if (singleCenterSample) {
  68119. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68120. }
  68121. else {
  68122. var sharedCell = j === centerIndex;
  68123. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68124. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68125. if (offsetLinear === 0) {
  68126. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68127. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68128. }
  68129. else {
  68130. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68131. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68132. }
  68133. }
  68134. }
  68135. for (var i = 0; i < linearSamplingMap.length; i++) {
  68136. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68137. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68138. }
  68139. // Replace with optimized
  68140. offsets = linearSamplingOffsets;
  68141. weights = linearSamplingWeights;
  68142. // Generate shaders
  68143. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68144. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68145. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68146. var defines = "";
  68147. defines += this._staticDefines;
  68148. for (var i = 0; i < varyingCount; i++) {
  68149. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68150. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68151. }
  68152. var depCount = 0;
  68153. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68154. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68155. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68156. depCount++;
  68157. }
  68158. if (this.packedFloat) {
  68159. defines += "#define PACKEDFLOAT 1";
  68160. }
  68161. _super.prototype.updateEffect.call(this, defines, null, null, {
  68162. varyingCount: varyingCount,
  68163. depCount: depCount
  68164. }, onCompiled, onError);
  68165. };
  68166. /**
  68167. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68168. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68169. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68170. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68171. * The gaps between physical kernels are compensated for in the weighting of the samples
  68172. * @param idealKernel Ideal blur kernel.
  68173. * @return Nearest best kernel.
  68174. */
  68175. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68176. var v = Math.round(idealKernel);
  68177. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68178. var k = _a[_i];
  68179. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68180. return Math.max(k, 3);
  68181. }
  68182. }
  68183. return Math.max(v, 3);
  68184. };
  68185. /**
  68186. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68187. * @param x The point on the Gaussian distribution to sample.
  68188. * @return the value of the Gaussian function at x.
  68189. */
  68190. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68191. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68192. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68193. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68194. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68195. // truncated at around 1.3% of peak strength.
  68196. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68197. var sigma = (1 / 3);
  68198. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68199. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68200. var weight = (1.0 / denominator) * Math.exp(exponent);
  68201. return weight;
  68202. };
  68203. /**
  68204. * Generates a string that can be used as a floating point number in GLSL.
  68205. * @param x Value to print.
  68206. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68207. * @return GLSL float string.
  68208. */
  68209. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68210. if (decimalFigures === void 0) { decimalFigures = 8; }
  68211. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68212. };
  68213. return BlurPostProcess;
  68214. }(BABYLON.PostProcess));
  68215. BABYLON.BlurPostProcess = BlurPostProcess;
  68216. })(BABYLON || (BABYLON = {}));
  68217. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68218. var BABYLON;
  68219. (function (BABYLON) {
  68220. /**
  68221. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  68222. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  68223. * based on samples that have a large difference in distance than the center pixel.
  68224. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68225. */
  68226. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  68227. __extends(DepthOfFieldBlurPostProcess, _super);
  68228. /**
  68229. * Creates a new instance of @see CircleOfConfusionPostProcess
  68230. * @param name The name of the effect.
  68231. * @param scene The scene the effect belongs to.
  68232. * @param direction The direction the blur should be applied.
  68233. * @param kernel The size of the kernel used to blur.
  68234. * @param options The required width/height ratio to downsize to before computing the render pass.
  68235. * @param camera The camera to apply the render pass to.
  68236. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  68237. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  68238. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68239. * @param engine The engine which the post process will be applied. (default: current engine)
  68240. * @param reusable If the post process can be reused on the same frame. (default: false)
  68241. * @param textureType Type of textures used when performing the post process. (default: 0)
  68242. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68243. */
  68244. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  68245. if (imageToBlur === void 0) { imageToBlur = null; }
  68246. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68247. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68248. if (blockCompilation === void 0) { blockCompilation = false; }
  68249. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  68250. _this.direction = direction;
  68251. _this.onApplyObservable.add(function (effect) {
  68252. if (imageToBlur != null) {
  68253. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  68254. }
  68255. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68256. if (scene.activeCamera) {
  68257. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  68258. }
  68259. });
  68260. return _this;
  68261. }
  68262. return DepthOfFieldBlurPostProcess;
  68263. }(BABYLON.BlurPostProcess));
  68264. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  68265. })(BABYLON || (BABYLON = {}));
  68266. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  68267. var BABYLON;
  68268. (function (BABYLON) {
  68269. /**
  68270. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  68271. */
  68272. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  68273. __extends(DepthOfFieldMergePostProcess, _super);
  68274. /**
  68275. * Creates a new instance of @see CircleOfConfusionPostProcess
  68276. * @param name The name of the effect.
  68277. * @param original The non-blurred image to be modified
  68278. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  68279. * @param blurSteps Incrimental bluring post processes.
  68280. * @param options The required width/height ratio to downsize to before computing the render pass.
  68281. * @param camera The camera to apply the render pass to.
  68282. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68283. * @param engine The engine which the post process will be applied. (default: current engine)
  68284. * @param reusable If the post process can be reused on the same frame. (default: false)
  68285. * @param textureType Type of textures used when performing the post process. (default: 0)
  68286. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68287. */
  68288. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68289. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68290. if (blockCompilation === void 0) { blockCompilation = false; }
  68291. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  68292. _this.blurSteps = blurSteps;
  68293. _this.onApplyObservable.add(function (effect) {
  68294. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  68295. effect.setTextureFromPostProcess("originalSampler", original);
  68296. blurSteps.forEach(function (step, index) {
  68297. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  68298. });
  68299. });
  68300. if (!blockCompilation) {
  68301. _this.updateEffect();
  68302. }
  68303. return _this;
  68304. }
  68305. /**
  68306. * Updates the effect with the current post process compile time values and recompiles the shader.
  68307. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68308. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68309. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68310. * @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
  68311. * @param onCompiled Called when the shader has been compiled.
  68312. * @param onError Called if there is an error when compiling a shader.
  68313. */
  68314. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68315. if (defines === void 0) { defines = null; }
  68316. if (uniforms === void 0) { uniforms = null; }
  68317. if (samplers === void 0) { samplers = null; }
  68318. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + this.blurSteps.length + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  68319. };
  68320. return DepthOfFieldMergePostProcess;
  68321. }(BABYLON.PostProcess));
  68322. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  68323. })(BABYLON || (BABYLON = {}));
  68324. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  68325. var BABYLON;
  68326. (function (BABYLON) {
  68327. /**
  68328. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  68329. */
  68330. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  68331. __extends(CircleOfConfusionPostProcess, _super);
  68332. /**
  68333. * Creates a new instance of @see CircleOfConfusionPostProcess
  68334. * @param name The name of the effect.
  68335. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  68336. * @param options The required width/height ratio to downsize to before computing the render pass.
  68337. * @param camera The camera to apply the render pass to.
  68338. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68339. * @param engine The engine which the post process will be applied. (default: current engine)
  68340. * @param reusable If the post process can be reused on the same frame. (default: false)
  68341. * @param textureType Type of textures used when performing the post process. (default: 0)
  68342. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68343. */
  68344. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68345. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68346. if (blockCompilation === void 0) { blockCompilation = false; }
  68347. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  68348. /**
  68349. * 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.
  68350. */
  68351. _this.lensSize = 50;
  68352. /**
  68353. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68354. */
  68355. _this.fStop = 1.4;
  68356. /**
  68357. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68358. */
  68359. _this.focusDistance = 2000;
  68360. /**
  68361. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  68362. */
  68363. _this.focalLength = 50;
  68364. _this._depthTexture = null;
  68365. _this._depthTexture = depthTexture;
  68366. _this.onApplyObservable.add(function (effect) {
  68367. if (!_this._depthTexture) {
  68368. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  68369. return;
  68370. }
  68371. effect.setTexture("depthSampler", _this._depthTexture);
  68372. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  68373. var aperture = _this.lensSize / _this.fStop;
  68374. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  68375. effect.setFloat('focusDistance', _this.focusDistance);
  68376. effect.setFloat('cocPrecalculation', cocPrecalculation);
  68377. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  68378. });
  68379. return _this;
  68380. }
  68381. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  68382. /**
  68383. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  68384. */
  68385. set: function (value) {
  68386. this._depthTexture = value;
  68387. },
  68388. enumerable: true,
  68389. configurable: true
  68390. });
  68391. return CircleOfConfusionPostProcess;
  68392. }(BABYLON.PostProcess));
  68393. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  68394. })(BABYLON || (BABYLON = {}));
  68395. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  68396. var BABYLON;
  68397. (function (BABYLON) {
  68398. /**
  68399. * Specifies the level of max blur that should be applied when using the depth of field effect
  68400. */
  68401. var DepthOfFieldEffectBlurLevel;
  68402. (function (DepthOfFieldEffectBlurLevel) {
  68403. /**
  68404. * Subtle blur
  68405. */
  68406. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  68407. /**
  68408. * Medium blur
  68409. */
  68410. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  68411. /**
  68412. * Large blur
  68413. */
  68414. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  68415. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  68416. ;
  68417. /**
  68418. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  68419. */
  68420. var DepthOfFieldEffect = /** @class */ (function (_super) {
  68421. __extends(DepthOfFieldEffect, _super);
  68422. /**
  68423. * Creates a new instance of @see DepthOfFieldEffect
  68424. * @param scene The scene the effect belongs to.
  68425. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  68426. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  68427. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68428. */
  68429. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  68430. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  68431. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  68432. if (blockCompilation === void 0) { blockCompilation = false; }
  68433. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  68434. return _this._effects;
  68435. }, true) || this;
  68436. _this._effects = [];
  68437. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  68438. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  68439. // Capture circle of confusion texture
  68440. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  68441. _this._depthOfFieldPass.autoClear = false;
  68442. // 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)
  68443. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  68444. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  68445. _this._depthOfFieldBlurY = [];
  68446. _this._depthOfFieldBlurX = [];
  68447. var blurCount = 1;
  68448. var kernelSize = 15;
  68449. switch (blurLevel) {
  68450. case DepthOfFieldEffectBlurLevel.High: {
  68451. blurCount = 3;
  68452. kernelSize = 51;
  68453. break;
  68454. }
  68455. case DepthOfFieldEffectBlurLevel.Medium: {
  68456. blurCount = 2;
  68457. kernelSize = 31;
  68458. break;
  68459. }
  68460. default: {
  68461. kernelSize = 15;
  68462. blurCount = 1;
  68463. break;
  68464. }
  68465. }
  68466. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  68467. for (var i = 0; i < blurCount; i++) {
  68468. 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, blockCompilation);
  68469. blurY.autoClear = false;
  68470. 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, blockCompilation);
  68471. blurX.autoClear = false;
  68472. _this._depthOfFieldBlurY.push(blurY);
  68473. _this._depthOfFieldBlurX.push(blurX);
  68474. }
  68475. // Merge blurred images with original image based on circleOfConfusion
  68476. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  68477. _this._depthOfFieldMerge.autoClear = false;
  68478. // Set all post processes on the effect.
  68479. _this._effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  68480. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  68481. _this._effects.push(_this._depthOfFieldBlurY[i]);
  68482. _this._effects.push(_this._depthOfFieldBlurX[i]);
  68483. }
  68484. _this._effects.push(_this._depthOfFieldMerge);
  68485. return _this;
  68486. }
  68487. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  68488. get: function () {
  68489. return this._circleOfConfusion.focalLength;
  68490. },
  68491. /**
  68492. * The focal the length of the camera used in the effect
  68493. */
  68494. set: function (value) {
  68495. this._circleOfConfusion.focalLength = value;
  68496. },
  68497. enumerable: true,
  68498. configurable: true
  68499. });
  68500. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  68501. get: function () {
  68502. return this._circleOfConfusion.fStop;
  68503. },
  68504. /**
  68505. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  68506. */
  68507. set: function (value) {
  68508. this._circleOfConfusion.fStop = value;
  68509. },
  68510. enumerable: true,
  68511. configurable: true
  68512. });
  68513. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  68514. get: function () {
  68515. return this._circleOfConfusion.focusDistance;
  68516. },
  68517. /**
  68518. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  68519. */
  68520. set: function (value) {
  68521. this._circleOfConfusion.focusDistance = value;
  68522. },
  68523. enumerable: true,
  68524. configurable: true
  68525. });
  68526. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  68527. get: function () {
  68528. return this._circleOfConfusion.lensSize;
  68529. },
  68530. /**
  68531. * 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.
  68532. */
  68533. set: function (value) {
  68534. this._circleOfConfusion.lensSize = value;
  68535. },
  68536. enumerable: true,
  68537. configurable: true
  68538. });
  68539. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  68540. /**
  68541. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  68542. */
  68543. set: function (value) {
  68544. this._circleOfConfusion.depthTexture = value;
  68545. },
  68546. enumerable: true,
  68547. configurable: true
  68548. });
  68549. /**
  68550. * Disposes each of the internal effects for a given camera.
  68551. * @param camera The camera to dispose the effect on.
  68552. */
  68553. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  68554. this._depthOfFieldPass.dispose(camera);
  68555. this._circleOfConfusion.dispose(camera);
  68556. this._depthOfFieldBlurX.forEach(function (element) {
  68557. element.dispose(camera);
  68558. });
  68559. this._depthOfFieldBlurY.forEach(function (element) {
  68560. element.dispose(camera);
  68561. });
  68562. this._depthOfFieldMerge.dispose(camera);
  68563. };
  68564. /**
  68565. * Internal
  68566. */
  68567. DepthOfFieldEffect.prototype._updateEffects = function () {
  68568. for (var effect in this._effects) {
  68569. this._effects[effect].updateEffect();
  68570. }
  68571. };
  68572. /**
  68573. * Internal
  68574. * @returns if all the contained post processes are ready.
  68575. */
  68576. DepthOfFieldEffect.prototype._isReady = function () {
  68577. for (var effect in this._effects) {
  68578. if (!this._effects[effect].isReady()) {
  68579. return false;
  68580. }
  68581. }
  68582. return true;
  68583. };
  68584. return DepthOfFieldEffect;
  68585. }(BABYLON.PostProcessRenderEffect));
  68586. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  68587. })(BABYLON || (BABYLON = {}));
  68588. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  68589. var BABYLON;
  68590. (function (BABYLON) {
  68591. /**
  68592. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  68593. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  68594. */
  68595. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  68596. __extends(DefaultRenderingPipeline, _super);
  68597. /**
  68598. * @constructor
  68599. * @param {string} name - The rendering pipeline name
  68600. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68601. * @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)
  68602. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68603. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  68604. */
  68605. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  68606. if (automaticBuild === void 0) { automaticBuild = true; }
  68607. var _this = _super.call(this, scene.getEngine(), name) || this;
  68608. _this._originalCameras = [];
  68609. /**
  68610. * ID of the sharpen post process,
  68611. */
  68612. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  68613. /**
  68614. * ID of the pass post process used for bloom,
  68615. */
  68616. _this.PassPostProcessId = "PassPostProcessEffect";
  68617. /**
  68618. * ID of the highlight post process used for bloom,
  68619. */
  68620. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  68621. /**
  68622. * ID of the blurX post process used for bloom,
  68623. */
  68624. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  68625. /**
  68626. * ID of the blurY post process used for bloom,
  68627. */
  68628. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  68629. /**
  68630. * ID of the copy back post process used for bloom,
  68631. */
  68632. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  68633. /**
  68634. * ID of the image processing post process;
  68635. */
  68636. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  68637. /**
  68638. * ID of the Fast Approximate Anti-Aliasing post process;
  68639. */
  68640. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  68641. /**
  68642. * ID of the final merge post process;
  68643. */
  68644. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  68645. /**
  68646. * ID of the chromatic aberration post process,
  68647. */
  68648. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  68649. /**
  68650. * Animations which can be used to tweak settings over a period of time
  68651. */
  68652. _this.animations = [];
  68653. // Values
  68654. _this._sharpenEnabled = false;
  68655. _this._bloomEnabled = false;
  68656. _this._depthOfFieldEnabled = false;
  68657. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  68658. _this._fxaaEnabled = false;
  68659. _this._msaaEnabled = false;
  68660. _this._imageProcessingEnabled = true;
  68661. _this._bloomScale = 0.6;
  68662. _this._chromaticAberrationEnabled = false;
  68663. _this._buildAllowed = true;
  68664. /**
  68665. * Specifies the size of the bloom blur kernel, relative to the final output size
  68666. */
  68667. _this.bloomKernel = 64;
  68668. /**
  68669. * Specifies the weight of the bloom in the final rendering
  68670. */
  68671. _this._bloomWeight = 0.15;
  68672. _this._prevPostProcess = null;
  68673. _this._prevPrevPostProcess = null;
  68674. _this._cameras = cameras || [];
  68675. _this._originalCameras = _this._cameras.slice();
  68676. _this._buildAllowed = automaticBuild;
  68677. // Initialize
  68678. _this._scene = scene;
  68679. var caps = _this._scene.getEngine().getCaps();
  68680. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  68681. // Misc
  68682. if (_this._hdr) {
  68683. if (caps.textureHalfFloatRender) {
  68684. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68685. }
  68686. else if (caps.textureFloatRender) {
  68687. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68688. }
  68689. }
  68690. else {
  68691. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68692. }
  68693. // Attach
  68694. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68695. var engine = _this._scene.getEngine();
  68696. // Create post processes before hand so they can be modified before enabled.
  68697. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  68698. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  68699. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  68700. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  68701. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  68702. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  68703. _this._buildPipeline();
  68704. return _this;
  68705. }
  68706. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  68707. get: function () {
  68708. return this._sharpenEnabled;
  68709. },
  68710. /**
  68711. * Enable or disable the sharpen process from the pipeline
  68712. */
  68713. set: function (enabled) {
  68714. if (this._sharpenEnabled === enabled) {
  68715. return;
  68716. }
  68717. this._sharpenEnabled = enabled;
  68718. this._buildPipeline();
  68719. },
  68720. enumerable: true,
  68721. configurable: true
  68722. });
  68723. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  68724. get: function () {
  68725. return this._bloomWeight;
  68726. },
  68727. /**
  68728. * The strength of the bloom.
  68729. */
  68730. set: function (value) {
  68731. if (this._bloomWeight === value) {
  68732. return;
  68733. }
  68734. this._bloomWeight = value;
  68735. if (this._hdr && this.copyBack) {
  68736. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  68737. }
  68738. },
  68739. enumerable: true,
  68740. configurable: true
  68741. });
  68742. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  68743. get: function () {
  68744. return this._bloomScale;
  68745. },
  68746. /**
  68747. * The scale of the bloom, lower value will provide better performance.
  68748. */
  68749. set: function (value) {
  68750. if (this._bloomScale === value) {
  68751. return;
  68752. }
  68753. this._bloomScale = value;
  68754. this._buildPipeline();
  68755. },
  68756. enumerable: true,
  68757. configurable: true
  68758. });
  68759. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  68760. get: function () {
  68761. return this._bloomEnabled;
  68762. },
  68763. /**
  68764. * Enable or disable the bloom from the pipeline
  68765. */
  68766. set: function (enabled) {
  68767. if (this._bloomEnabled === enabled) {
  68768. return;
  68769. }
  68770. this._bloomEnabled = enabled;
  68771. this._buildPipeline();
  68772. },
  68773. enumerable: true,
  68774. configurable: true
  68775. });
  68776. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  68777. /**
  68778. * If the depth of field is enabled.
  68779. */
  68780. get: function () {
  68781. return this._depthOfFieldEnabled;
  68782. },
  68783. set: function (enabled) {
  68784. if (this._depthOfFieldEnabled === enabled) {
  68785. return;
  68786. }
  68787. this._depthOfFieldEnabled = enabled;
  68788. this._buildPipeline();
  68789. },
  68790. enumerable: true,
  68791. configurable: true
  68792. });
  68793. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  68794. /**
  68795. * Blur level of the depth of field effect. (Higher blur will effect performance)
  68796. */
  68797. get: function () {
  68798. return this._depthOfFieldBlurLevel;
  68799. },
  68800. set: function (value) {
  68801. if (this._depthOfFieldBlurLevel === value) {
  68802. return;
  68803. }
  68804. this._depthOfFieldBlurLevel = value;
  68805. // recreate dof and dispose old as this setting is not dynamic
  68806. var oldDof = this.depthOfField;
  68807. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  68808. this.depthOfField.focalLength = oldDof.focalLength;
  68809. this.depthOfField.focusDistance = oldDof.focusDistance;
  68810. this.depthOfField.fStop = oldDof.fStop;
  68811. this.depthOfField.lensSize = oldDof.lensSize;
  68812. for (var i = 0; i < this._cameras.length; i++) {
  68813. oldDof.disposeEffects(this._cameras[i]);
  68814. }
  68815. this._buildPipeline();
  68816. },
  68817. enumerable: true,
  68818. configurable: true
  68819. });
  68820. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  68821. get: function () {
  68822. return this._fxaaEnabled;
  68823. },
  68824. /**
  68825. * If the anti aliasing is enabled.
  68826. */
  68827. set: function (enabled) {
  68828. if (this._fxaaEnabled === enabled) {
  68829. return;
  68830. }
  68831. this._fxaaEnabled = enabled;
  68832. this._buildPipeline();
  68833. },
  68834. enumerable: true,
  68835. configurable: true
  68836. });
  68837. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  68838. get: function () {
  68839. return this._msaaEnabled;
  68840. },
  68841. /**
  68842. * If the multisample anti-aliasing is enabled.
  68843. */
  68844. set: function (enabled) {
  68845. if (this._msaaEnabled === enabled) {
  68846. return;
  68847. }
  68848. this._msaaEnabled = enabled;
  68849. this._buildPipeline();
  68850. },
  68851. enumerable: true,
  68852. configurable: true
  68853. });
  68854. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  68855. get: function () {
  68856. return this._imageProcessingEnabled;
  68857. },
  68858. /**
  68859. * If image processing is enabled.
  68860. */
  68861. set: function (enabled) {
  68862. if (this._imageProcessingEnabled === enabled) {
  68863. return;
  68864. }
  68865. this._imageProcessingEnabled = enabled;
  68866. this._buildPipeline();
  68867. },
  68868. enumerable: true,
  68869. configurable: true
  68870. });
  68871. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  68872. get: function () {
  68873. return this._chromaticAberrationEnabled;
  68874. },
  68875. /**
  68876. * Enable or disable the chromaticAberration process from the pipeline
  68877. */
  68878. set: function (enabled) {
  68879. if (this._chromaticAberrationEnabled === enabled) {
  68880. return;
  68881. }
  68882. this._chromaticAberrationEnabled = enabled;
  68883. this._buildPipeline();
  68884. },
  68885. enumerable: true,
  68886. configurable: true
  68887. });
  68888. /**
  68889. * Force the compilation of the entire pipeline.
  68890. */
  68891. DefaultRenderingPipeline.prototype.prepare = function () {
  68892. var previousState = this._buildAllowed;
  68893. this._buildAllowed = true;
  68894. this._buildPipeline();
  68895. this._buildAllowed = previousState;
  68896. };
  68897. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  68898. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  68899. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  68900. postProcess.autoClear = false;
  68901. }
  68902. else {
  68903. postProcess.autoClear = true;
  68904. }
  68905. if (!skipTextureSharing) {
  68906. if (this._prevPrevPostProcess) {
  68907. postProcess.shareOutputWith(this._prevPrevPostProcess);
  68908. }
  68909. else {
  68910. postProcess.useOwnOutput();
  68911. }
  68912. if (this._prevPostProcess) {
  68913. this._prevPrevPostProcess = this._prevPostProcess;
  68914. }
  68915. this._prevPostProcess = postProcess;
  68916. }
  68917. };
  68918. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  68919. var _this = this;
  68920. if (!this._buildAllowed) {
  68921. return;
  68922. }
  68923. var engine = this._scene.getEngine();
  68924. this._disposePostProcesses();
  68925. if (this._cameras !== null) {
  68926. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68927. // get back cameras to be used to reattach pipeline
  68928. this._cameras = this._originalCameras.slice();
  68929. }
  68930. this._reset();
  68931. this._prevPostProcess = null;
  68932. this._prevPrevPostProcess = null;
  68933. if (this.sharpenEnabled) {
  68934. if (!this.sharpen.isReady()) {
  68935. this.sharpen.updateEffect();
  68936. }
  68937. this.addEffect(this._sharpenEffect);
  68938. this._setAutoClearAndTextureSharing(this.sharpen);
  68939. }
  68940. if (this.depthOfFieldEnabled) {
  68941. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  68942. this.depthOfField.depthTexture = depthTexture;
  68943. if (!this.depthOfField._isReady()) {
  68944. this.depthOfField._updateEffects();
  68945. }
  68946. this.addEffect(this.depthOfField);
  68947. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  68948. }
  68949. if (this.bloomEnabled) {
  68950. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68951. this._setAutoClearAndTextureSharing(this.pass, true);
  68952. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  68953. if (!this._hdr) {
  68954. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68955. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  68956. this.highlights.autoClear = false;
  68957. this.highlights.alwaysForcePOT = true;
  68958. }
  68959. 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);
  68960. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  68961. this.blurX.alwaysForcePOT = true;
  68962. this.blurX.autoClear = false;
  68963. this.blurX.onActivateObservable.add(function () {
  68964. var dw = _this.blurX.width / engine.getRenderWidth(true);
  68965. _this.blurX.kernel = _this.bloomKernel * dw;
  68966. });
  68967. 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);
  68968. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  68969. this.blurY.alwaysForcePOT = true;
  68970. this.blurY.autoClear = false;
  68971. this.blurY.onActivateObservable.add(function () {
  68972. var dh = _this.blurY.height / engine.getRenderHeight(true);
  68973. _this.blurY.kernel = _this.bloomKernel * dh;
  68974. });
  68975. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68976. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  68977. this.copyBack.alwaysForcePOT = true;
  68978. if (this._hdr) {
  68979. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  68980. var w = this.bloomWeight;
  68981. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  68982. }
  68983. else {
  68984. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  68985. }
  68986. this.copyBack.autoClear = false;
  68987. }
  68988. if (this._imageProcessingEnabled) {
  68989. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68990. if (this._hdr) {
  68991. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  68992. }
  68993. else {
  68994. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  68995. }
  68996. }
  68997. if (this._hdr && this.imageProcessing) {
  68998. this.finalMerge = this.imageProcessing;
  68999. }
  69000. else {
  69001. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69002. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  69003. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  69004. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  69005. }
  69006. if (this.bloomEnabled) {
  69007. if (this._hdr) {
  69008. this.copyBack.shareOutputWith(this.blurX);
  69009. if (this.imageProcessing) {
  69010. this.imageProcessing.shareOutputWith(this.pass);
  69011. this.imageProcessing.autoClear = false;
  69012. }
  69013. else {
  69014. this.finalMerge.shareOutputWith(this.pass);
  69015. }
  69016. }
  69017. else {
  69018. this.finalMerge.shareOutputWith(this.pass);
  69019. }
  69020. }
  69021. if (this.fxaaEnabled) {
  69022. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69023. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  69024. this._setAutoClearAndTextureSharing(this.fxaa);
  69025. }
  69026. if (this.chromaticAberrationEnabled) {
  69027. if (!this.chromaticAberration.isReady()) {
  69028. this.chromaticAberration.updateEffect();
  69029. }
  69030. this.addEffect(this._chromaticAberrationEffect);
  69031. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  69032. }
  69033. if (this._cameras !== null) {
  69034. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69035. }
  69036. if (this.msaaEnabled) {
  69037. if (!this._enableMSAAOnFirstPostProcess()) {
  69038. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  69039. }
  69040. }
  69041. };
  69042. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  69043. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  69044. for (var i = 0; i < this._cameras.length; i++) {
  69045. var camera = this._cameras[i];
  69046. if (this.pass) {
  69047. this.pass.dispose(camera);
  69048. }
  69049. if (this.highlights) {
  69050. this.highlights.dispose(camera);
  69051. }
  69052. if (this.blurX) {
  69053. this.blurX.dispose(camera);
  69054. }
  69055. if (this.blurY) {
  69056. this.blurY.dispose(camera);
  69057. }
  69058. if (this.copyBack) {
  69059. this.copyBack.dispose(camera);
  69060. }
  69061. if (this.imageProcessing) {
  69062. this.imageProcessing.dispose(camera);
  69063. }
  69064. if (this.fxaa) {
  69065. this.fxaa.dispose(camera);
  69066. }
  69067. if (this.finalMerge) {
  69068. this.finalMerge.dispose(camera);
  69069. }
  69070. // These are created in the constructor and should not be disposed on every pipeline change
  69071. if (disposeNonRecreated) {
  69072. if (this.sharpen) {
  69073. this.sharpen.dispose(camera);
  69074. }
  69075. if (this.depthOfField) {
  69076. this.depthOfField.disposeEffects(camera);
  69077. }
  69078. if (this.chromaticAberration) {
  69079. this.chromaticAberration.dispose(camera);
  69080. }
  69081. }
  69082. }
  69083. this.pass = null;
  69084. this.highlights = null;
  69085. this.blurX = null;
  69086. this.blurY = null;
  69087. this.copyBack = null;
  69088. this.imageProcessing = null;
  69089. this.fxaa = null;
  69090. this.finalMerge = null;
  69091. if (disposeNonRecreated) {
  69092. this.sharpen = null;
  69093. this.depthOfField = null;
  69094. this.chromaticAberration = null;
  69095. }
  69096. };
  69097. /**
  69098. * Dispose of the pipeline and stop all post processes
  69099. */
  69100. DefaultRenderingPipeline.prototype.dispose = function () {
  69101. this._disposePostProcesses(true);
  69102. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69103. _super.prototype.dispose.call(this);
  69104. };
  69105. /**
  69106. * Serialize the rendering pipeline (Used when exporting)
  69107. * @returns the serialized object
  69108. */
  69109. DefaultRenderingPipeline.prototype.serialize = function () {
  69110. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69111. serializationObject.customType = "DefaultRenderingPipeline";
  69112. return serializationObject;
  69113. };
  69114. /**
  69115. * Parse the serialized pipeline
  69116. * @param source Source pipeline.
  69117. * @param scene The scene to load the pipeline to.
  69118. * @param rootUrl The URL of the serialized pipeline.
  69119. * @returns An instantiated pipeline from the serialized object.
  69120. */
  69121. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69122. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  69123. };
  69124. __decorate([
  69125. BABYLON.serialize()
  69126. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  69127. __decorate([
  69128. BABYLON.serialize()
  69129. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  69130. __decorate([
  69131. BABYLON.serialize()
  69132. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  69133. __decorate([
  69134. BABYLON.serialize()
  69135. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  69136. __decorate([
  69137. BABYLON.serialize()
  69138. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  69139. __decorate([
  69140. BABYLON.serialize()
  69141. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  69142. __decorate([
  69143. BABYLON.serialize()
  69144. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  69145. __decorate([
  69146. BABYLON.serialize()
  69147. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  69148. __decorate([
  69149. BABYLON.serialize()
  69150. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  69151. __decorate([
  69152. BABYLON.serialize()
  69153. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  69154. __decorate([
  69155. BABYLON.serialize()
  69156. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  69157. __decorate([
  69158. BABYLON.serialize()
  69159. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  69160. __decorate([
  69161. BABYLON.serialize()
  69162. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  69163. return DefaultRenderingPipeline;
  69164. }(BABYLON.PostProcessRenderPipeline));
  69165. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  69166. })(BABYLON || (BABYLON = {}));
  69167. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  69168. var BABYLON;
  69169. (function (BABYLON) {
  69170. /**
  69171. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  69172. */
  69173. var GeometryBufferRenderer = /** @class */ (function () {
  69174. /**
  69175. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  69176. * @param scene The scene the buffer belongs to
  69177. * @param ratio How big is the buffer related to the main canvas.
  69178. */
  69179. function GeometryBufferRenderer(scene, ratio) {
  69180. if (ratio === void 0) { ratio = 1; }
  69181. this._enablePosition = false;
  69182. this._scene = scene;
  69183. this._ratio = ratio;
  69184. // Render target
  69185. this._createRenderTargets();
  69186. }
  69187. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  69188. /**
  69189. * Set the render list (meshes to be rendered) used in the G buffer.
  69190. */
  69191. set: function (meshes) {
  69192. this._multiRenderTarget.renderList = meshes;
  69193. },
  69194. enumerable: true,
  69195. configurable: true
  69196. });
  69197. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  69198. /**
  69199. * Gets wether or not G buffer are supported by the running hardware.
  69200. * This requires draw buffer supports
  69201. */
  69202. get: function () {
  69203. return this._multiRenderTarget.isSupported;
  69204. },
  69205. enumerable: true,
  69206. configurable: true
  69207. });
  69208. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  69209. /**
  69210. * Gets wether or not position are enabled for the G buffer.
  69211. */
  69212. get: function () {
  69213. return this._enablePosition;
  69214. },
  69215. /**
  69216. * Sets wether or not position are enabled for the G buffer.
  69217. */
  69218. set: function (enable) {
  69219. this._enablePosition = enable;
  69220. this.dispose();
  69221. this._createRenderTargets();
  69222. },
  69223. enumerable: true,
  69224. configurable: true
  69225. });
  69226. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  69227. /**
  69228. * Gets the scene associated with the buffer.
  69229. */
  69230. get: function () {
  69231. return this._scene;
  69232. },
  69233. enumerable: true,
  69234. configurable: true
  69235. });
  69236. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  69237. /**
  69238. * Gets the ratio used by the buffer during its creation.
  69239. * How big is the buffer related to the main canvas.
  69240. */
  69241. get: function () {
  69242. return this._ratio;
  69243. },
  69244. enumerable: true,
  69245. configurable: true
  69246. });
  69247. /**
  69248. * Checks wether everything is ready to render a submesh to the G buffer.
  69249. * @param subMesh the submesh to check readiness for
  69250. * @param useInstances is the mesh drawn using instance or not
  69251. * @returns true if ready otherwise false
  69252. */
  69253. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  69254. var material = subMesh.getMaterial();
  69255. if (material && material.disableDepthWrite) {
  69256. return false;
  69257. }
  69258. var defines = [];
  69259. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  69260. var mesh = subMesh.getMesh();
  69261. // Alpha test
  69262. if (material && material.needAlphaTesting()) {
  69263. defines.push("#define ALPHATEST");
  69264. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69265. attribs.push(BABYLON.VertexBuffer.UVKind);
  69266. defines.push("#define UV1");
  69267. }
  69268. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69269. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69270. defines.push("#define UV2");
  69271. }
  69272. }
  69273. // Buffers
  69274. if (this._enablePosition) {
  69275. defines.push("#define POSITION");
  69276. }
  69277. // Bones
  69278. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69279. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69280. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69281. if (mesh.numBoneInfluencers > 4) {
  69282. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69283. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69284. }
  69285. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69286. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  69287. }
  69288. else {
  69289. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69290. }
  69291. // Instances
  69292. if (useInstances) {
  69293. defines.push("#define INSTANCES");
  69294. attribs.push("world0");
  69295. attribs.push("world1");
  69296. attribs.push("world2");
  69297. attribs.push("world3");
  69298. }
  69299. // Get correct effect
  69300. var join = defines.join("\n");
  69301. if (this._cachedDefines !== join) {
  69302. this._cachedDefines = join;
  69303. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  69304. }
  69305. return this._effect.isReady();
  69306. };
  69307. /**
  69308. * Gets the current underlying G Buffer.
  69309. * @returns the buffer
  69310. */
  69311. GeometryBufferRenderer.prototype.getGBuffer = function () {
  69312. return this._multiRenderTarget;
  69313. };
  69314. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  69315. /**
  69316. * Gets the number of samples used to render the buffer (anti aliasing).
  69317. */
  69318. get: function () {
  69319. return this._multiRenderTarget.samples;
  69320. },
  69321. /**
  69322. * Sets the number of samples used to render the buffer (anti aliasing).
  69323. */
  69324. set: function (value) {
  69325. this._multiRenderTarget.samples = value;
  69326. },
  69327. enumerable: true,
  69328. configurable: true
  69329. });
  69330. /**
  69331. * Disposes the renderer and frees up associated resources.
  69332. */
  69333. GeometryBufferRenderer.prototype.dispose = function () {
  69334. this.getGBuffer().dispose();
  69335. };
  69336. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  69337. var _this = this;
  69338. var engine = this._scene.getEngine();
  69339. var count = this._enablePosition ? 3 : 2;
  69340. 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 });
  69341. if (!this.isSupported) {
  69342. return;
  69343. }
  69344. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69345. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69346. this._multiRenderTarget.refreshRate = 1;
  69347. this._multiRenderTarget.renderParticles = false;
  69348. this._multiRenderTarget.renderList = null;
  69349. // set default depth value to 1.0 (far away)
  69350. this._multiRenderTarget.onClearObservable.add(function (engine) {
  69351. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  69352. });
  69353. // Custom render function
  69354. var renderSubMesh = function (subMesh) {
  69355. var mesh = subMesh.getRenderingMesh();
  69356. var scene = _this._scene;
  69357. var engine = scene.getEngine();
  69358. var material = subMesh.getMaterial();
  69359. if (!material) {
  69360. return;
  69361. }
  69362. // Culling
  69363. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  69364. // Managing instances
  69365. var batch = mesh._getInstancesRenderList(subMesh._id);
  69366. if (batch.mustReturn) {
  69367. return;
  69368. }
  69369. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69370. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  69371. engine.enableEffect(_this._effect);
  69372. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  69373. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  69374. _this._effect.setMatrix("view", scene.getViewMatrix());
  69375. // Alpha test
  69376. if (material && material.needAlphaTesting()) {
  69377. var alphaTexture = material.getAlphaTestTexture();
  69378. if (alphaTexture) {
  69379. _this._effect.setTexture("diffuseSampler", alphaTexture);
  69380. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69381. }
  69382. }
  69383. // Bones
  69384. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69385. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69386. }
  69387. // Draw
  69388. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  69389. }
  69390. };
  69391. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69392. var index;
  69393. if (depthOnlySubMeshes.length) {
  69394. engine.setColorWrite(false);
  69395. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69396. renderSubMesh(depthOnlySubMeshes.data[index]);
  69397. }
  69398. engine.setColorWrite(true);
  69399. }
  69400. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69401. renderSubMesh(opaqueSubMeshes.data[index]);
  69402. }
  69403. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69404. renderSubMesh(alphaTestSubMeshes.data[index]);
  69405. }
  69406. };
  69407. };
  69408. return GeometryBufferRenderer;
  69409. }());
  69410. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  69411. })(BABYLON || (BABYLON = {}));
  69412. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  69413. var BABYLON;
  69414. (function (BABYLON) {
  69415. var RefractionPostProcess = /** @class */ (function (_super) {
  69416. __extends(RefractionPostProcess, _super);
  69417. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  69418. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  69419. _this.color = color;
  69420. _this.depth = depth;
  69421. _this.colorLevel = colorLevel;
  69422. _this._ownRefractionTexture = true;
  69423. _this.onActivateObservable.add(function (cam) {
  69424. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  69425. });
  69426. _this.onApplyObservable.add(function (effect) {
  69427. effect.setColor3("baseColor", _this.color);
  69428. effect.setFloat("depth", _this.depth);
  69429. effect.setFloat("colorLevel", _this.colorLevel);
  69430. effect.setTexture("refractionSampler", _this._refTexture);
  69431. });
  69432. return _this;
  69433. }
  69434. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  69435. /**
  69436. * Gets or sets the refraction texture
  69437. * Please note that you are responsible for disposing the texture if you set it manually
  69438. */
  69439. get: function () {
  69440. return this._refTexture;
  69441. },
  69442. set: function (value) {
  69443. if (this._refTexture && this._ownRefractionTexture) {
  69444. this._refTexture.dispose();
  69445. }
  69446. this._refTexture = value;
  69447. this._ownRefractionTexture = false;
  69448. },
  69449. enumerable: true,
  69450. configurable: true
  69451. });
  69452. // Methods
  69453. RefractionPostProcess.prototype.dispose = function (camera) {
  69454. if (this._refTexture && this._ownRefractionTexture) {
  69455. this._refTexture.dispose();
  69456. this._refTexture = null;
  69457. }
  69458. _super.prototype.dispose.call(this, camera);
  69459. };
  69460. return RefractionPostProcess;
  69461. }(BABYLON.PostProcess));
  69462. BABYLON.RefractionPostProcess = RefractionPostProcess;
  69463. })(BABYLON || (BABYLON = {}));
  69464. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  69465. var BABYLON;
  69466. (function (BABYLON) {
  69467. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  69468. __extends(BlackAndWhitePostProcess, _super);
  69469. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  69470. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  69471. _this.degree = 1;
  69472. _this.onApplyObservable.add(function (effect) {
  69473. effect.setFloat("degree", _this.degree);
  69474. });
  69475. return _this;
  69476. }
  69477. return BlackAndWhitePostProcess;
  69478. }(BABYLON.PostProcess));
  69479. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  69480. })(BABYLON || (BABYLON = {}));
  69481. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  69482. var BABYLON;
  69483. (function (BABYLON) {
  69484. /**
  69485. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  69486. * input texture to perform effects such as edge detection or sharpening
  69487. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69488. */
  69489. var ConvolutionPostProcess = /** @class */ (function (_super) {
  69490. __extends(ConvolutionPostProcess, _super);
  69491. /**
  69492. * Creates a new instance of @see ConvolutionPostProcess
  69493. * @param name The name of the effect.
  69494. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  69495. * @param options The required width/height ratio to downsize to before computing the render pass.
  69496. * @param camera The camera to apply the render pass to.
  69497. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69498. * @param engine The engine which the post process will be applied. (default: current engine)
  69499. * @param reusable If the post process can be reused on the same frame. (default: false)
  69500. * @param textureType Type of textures used when performing the post process. (default: 0)
  69501. */
  69502. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  69503. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69504. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69505. _this.kernel = kernel;
  69506. _this.onApply = function (effect) {
  69507. effect.setFloat2("screenSize", _this.width, _this.height);
  69508. effect.setArray("kernel", _this.kernel);
  69509. };
  69510. return _this;
  69511. }
  69512. // Statics
  69513. /**
  69514. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69515. */
  69516. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  69517. /**
  69518. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69519. */
  69520. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  69521. /**
  69522. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69523. */
  69524. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  69525. /**
  69526. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69527. */
  69528. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  69529. /**
  69530. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69531. */
  69532. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  69533. /**
  69534. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  69535. */
  69536. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  69537. return ConvolutionPostProcess;
  69538. }(BABYLON.PostProcess));
  69539. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  69540. })(BABYLON || (BABYLON = {}));
  69541. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  69542. var BABYLON;
  69543. (function (BABYLON) {
  69544. var FilterPostProcess = /** @class */ (function (_super) {
  69545. __extends(FilterPostProcess, _super);
  69546. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  69547. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  69548. _this.kernelMatrix = kernelMatrix;
  69549. _this.onApply = function (effect) {
  69550. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  69551. };
  69552. return _this;
  69553. }
  69554. return FilterPostProcess;
  69555. }(BABYLON.PostProcess));
  69556. BABYLON.FilterPostProcess = FilterPostProcess;
  69557. })(BABYLON || (BABYLON = {}));
  69558. //# sourceMappingURL=babylon.filterPostProcess.js.map
  69559. var BABYLON;
  69560. (function (BABYLON) {
  69561. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  69562. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  69563. __extends(VolumetricLightScatteringPostProcess, _super);
  69564. /**
  69565. * @constructor
  69566. * @param {string} name - The post-process name
  69567. * @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)
  69568. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  69569. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  69570. * @param {number} samples - The post-process quality, default 100
  69571. * @param {number} samplingMode - The post-process filtering mode
  69572. * @param {BABYLON.Engine} engine - The babylon engine
  69573. * @param {boolean} reusable - If the post-process is reusable
  69574. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  69575. */
  69576. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  69577. if (samples === void 0) { samples = 100; }
  69578. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69579. 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;
  69580. _this._screenCoordinates = BABYLON.Vector2.Zero();
  69581. /**
  69582. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  69583. * @type {Vector3}
  69584. */
  69585. _this.customMeshPosition = BABYLON.Vector3.Zero();
  69586. /**
  69587. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  69588. * @type {boolean}
  69589. */
  69590. _this.useCustomMeshPosition = false;
  69591. /**
  69592. * If the post-process should inverse the light scattering direction
  69593. * @type {boolean}
  69594. */
  69595. _this.invert = true;
  69596. /**
  69597. * Array containing the excluded meshes not rendered in the internal pass
  69598. */
  69599. _this.excludedMeshes = new Array();
  69600. /**
  69601. * Controls the overall intensity of the post-process
  69602. * @type {number}
  69603. */
  69604. _this.exposure = 0.3;
  69605. /**
  69606. * Dissipates each sample's contribution in range [0, 1]
  69607. * @type {number}
  69608. */
  69609. _this.decay = 0.96815;
  69610. /**
  69611. * Controls the overall intensity of each sample
  69612. * @type {number}
  69613. */
  69614. _this.weight = 0.58767;
  69615. /**
  69616. * Controls the density of each sample
  69617. * @type {number}
  69618. */
  69619. _this.density = 0.926;
  69620. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  69621. engine = scene.getEngine();
  69622. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  69623. // Configure mesh
  69624. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  69625. // Configure
  69626. _this._createPass(scene, ratio.passRatio || ratio);
  69627. _this.onActivate = function (camera) {
  69628. if (!_this.isSupported) {
  69629. _this.dispose(camera);
  69630. }
  69631. _this.onActivate = null;
  69632. };
  69633. _this.onApplyObservable.add(function (effect) {
  69634. _this._updateMeshScreenCoordinates(scene);
  69635. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  69636. effect.setFloat("exposure", _this.exposure);
  69637. effect.setFloat("decay", _this.decay);
  69638. effect.setFloat("weight", _this.weight);
  69639. effect.setFloat("density", _this.density);
  69640. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  69641. });
  69642. return _this;
  69643. }
  69644. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  69645. get: function () {
  69646. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69647. return false;
  69648. },
  69649. set: function (useDiffuseColor) {
  69650. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  69651. },
  69652. enumerable: true,
  69653. configurable: true
  69654. });
  69655. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  69656. return "VolumetricLightScatteringPostProcess";
  69657. };
  69658. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  69659. var mesh = subMesh.getMesh();
  69660. // Render this.mesh as default
  69661. if (mesh === this.mesh && mesh.material) {
  69662. return mesh.material.isReady(mesh);
  69663. }
  69664. var defines = [];
  69665. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69666. var material = subMesh.getMaterial();
  69667. // Alpha test
  69668. if (material) {
  69669. if (material.needAlphaTesting()) {
  69670. defines.push("#define ALPHATEST");
  69671. }
  69672. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69673. attribs.push(BABYLON.VertexBuffer.UVKind);
  69674. defines.push("#define UV1");
  69675. }
  69676. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69677. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69678. defines.push("#define UV2");
  69679. }
  69680. }
  69681. // Bones
  69682. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69683. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69684. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69685. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69686. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  69687. }
  69688. else {
  69689. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69690. }
  69691. // Instances
  69692. if (useInstances) {
  69693. defines.push("#define INSTANCES");
  69694. attribs.push("world0");
  69695. attribs.push("world1");
  69696. attribs.push("world2");
  69697. attribs.push("world3");
  69698. }
  69699. // Get correct effect
  69700. var join = defines.join("\n");
  69701. if (this._cachedDefines !== join) {
  69702. this._cachedDefines = join;
  69703. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  69704. }
  69705. return this._volumetricLightScatteringPass.isReady();
  69706. };
  69707. /**
  69708. * Sets the new light position for light scattering effect
  69709. * @param {BABYLON.Vector3} The new custom light position
  69710. */
  69711. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  69712. this.customMeshPosition = position;
  69713. };
  69714. /**
  69715. * Returns the light position for light scattering effect
  69716. * @return {BABYLON.Vector3} The custom light position
  69717. */
  69718. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  69719. return this.customMeshPosition;
  69720. };
  69721. /**
  69722. * Disposes the internal assets and detaches the post-process from the camera
  69723. */
  69724. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  69725. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  69726. if (rttIndex !== -1) {
  69727. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  69728. }
  69729. this._volumetricLightScatteringRTT.dispose();
  69730. _super.prototype.dispose.call(this, camera);
  69731. };
  69732. /**
  69733. * Returns the render target texture used by the post-process
  69734. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  69735. */
  69736. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  69737. return this._volumetricLightScatteringRTT;
  69738. };
  69739. // Private methods
  69740. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  69741. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  69742. return true;
  69743. }
  69744. return false;
  69745. };
  69746. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  69747. var _this = this;
  69748. var engine = scene.getEngine();
  69749. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69750. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69751. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69752. this._volumetricLightScatteringRTT.renderList = null;
  69753. this._volumetricLightScatteringRTT.renderParticles = false;
  69754. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  69755. var camera = this.getCamera();
  69756. if (camera) {
  69757. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69758. }
  69759. else {
  69760. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69761. }
  69762. // Custom render function for submeshes
  69763. var renderSubMesh = function (subMesh) {
  69764. var mesh = subMesh.getRenderingMesh();
  69765. if (_this._meshExcluded(mesh)) {
  69766. return;
  69767. }
  69768. var material = subMesh.getMaterial();
  69769. if (!material) {
  69770. return;
  69771. }
  69772. var scene = mesh.getScene();
  69773. var engine = scene.getEngine();
  69774. // Culling
  69775. engine.setState(material.backFaceCulling);
  69776. // Managing instances
  69777. var batch = mesh._getInstancesRenderList(subMesh._id);
  69778. if (batch.mustReturn) {
  69779. return;
  69780. }
  69781. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69782. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  69783. var effect = _this._volumetricLightScatteringPass;
  69784. if (mesh === _this.mesh) {
  69785. if (subMesh.effect) {
  69786. effect = subMesh.effect;
  69787. }
  69788. else {
  69789. effect = material.getEffect();
  69790. }
  69791. }
  69792. engine.enableEffect(effect);
  69793. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  69794. if (mesh === _this.mesh) {
  69795. material.bind(mesh.getWorldMatrix(), mesh);
  69796. }
  69797. else {
  69798. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  69799. // Alpha test
  69800. if (material && material.needAlphaTesting()) {
  69801. var alphaTexture = material.getAlphaTestTexture();
  69802. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  69803. if (alphaTexture) {
  69804. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69805. }
  69806. }
  69807. // Bones
  69808. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69809. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69810. }
  69811. }
  69812. // Draw
  69813. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  69814. }
  69815. };
  69816. // Render target texture callbacks
  69817. var savedSceneClearColor;
  69818. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  69819. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  69820. savedSceneClearColor = scene.clearColor;
  69821. scene.clearColor = sceneClearColor;
  69822. });
  69823. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  69824. scene.clearColor = savedSceneClearColor;
  69825. });
  69826. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69827. var engine = scene.getEngine();
  69828. var index;
  69829. if (depthOnlySubMeshes.length) {
  69830. engine.setColorWrite(false);
  69831. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69832. renderSubMesh(depthOnlySubMeshes.data[index]);
  69833. }
  69834. engine.setColorWrite(true);
  69835. }
  69836. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69837. renderSubMesh(opaqueSubMeshes.data[index]);
  69838. }
  69839. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69840. renderSubMesh(alphaTestSubMeshes.data[index]);
  69841. }
  69842. if (transparentSubMeshes.length) {
  69843. // Sort sub meshes
  69844. for (index = 0; index < transparentSubMeshes.length; index++) {
  69845. var submesh = transparentSubMeshes.data[index];
  69846. var boundingInfo = submesh.getBoundingInfo();
  69847. if (boundingInfo && scene.activeCamera) {
  69848. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  69849. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  69850. }
  69851. }
  69852. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  69853. sortedArray.sort(function (a, b) {
  69854. // Alpha index first
  69855. if (a._alphaIndex > b._alphaIndex) {
  69856. return 1;
  69857. }
  69858. if (a._alphaIndex < b._alphaIndex) {
  69859. return -1;
  69860. }
  69861. // Then distance to camera
  69862. if (a._distanceToCamera < b._distanceToCamera) {
  69863. return 1;
  69864. }
  69865. if (a._distanceToCamera > b._distanceToCamera) {
  69866. return -1;
  69867. }
  69868. return 0;
  69869. });
  69870. // Render sub meshes
  69871. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  69872. for (index = 0; index < sortedArray.length; index++) {
  69873. renderSubMesh(sortedArray[index]);
  69874. }
  69875. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69876. }
  69877. };
  69878. };
  69879. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  69880. var transform = scene.getTransformMatrix();
  69881. var meshPosition;
  69882. if (this.useCustomMeshPosition) {
  69883. meshPosition = this.customMeshPosition;
  69884. }
  69885. else if (this.attachedNode) {
  69886. meshPosition = this.attachedNode.position;
  69887. }
  69888. else {
  69889. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  69890. }
  69891. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  69892. this._screenCoordinates.x = pos.x / this._viewPort.width;
  69893. this._screenCoordinates.y = pos.y / this._viewPort.height;
  69894. if (this.invert)
  69895. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  69896. };
  69897. // Static methods
  69898. /**
  69899. * Creates a default mesh for the Volumeric Light Scattering post-process
  69900. * @param {string} The mesh name
  69901. * @param {BABYLON.Scene} The scene where to create the mesh
  69902. * @return {BABYLON.Mesh} the default mesh
  69903. */
  69904. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  69905. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  69906. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  69907. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  69908. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  69909. mesh.material = material;
  69910. return mesh;
  69911. };
  69912. __decorate([
  69913. BABYLON.serializeAsVector3()
  69914. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  69915. __decorate([
  69916. BABYLON.serialize()
  69917. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  69918. __decorate([
  69919. BABYLON.serialize()
  69920. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  69921. __decorate([
  69922. BABYLON.serializeAsMeshReference()
  69923. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  69924. __decorate([
  69925. BABYLON.serialize()
  69926. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  69927. __decorate([
  69928. BABYLON.serialize()
  69929. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  69930. __decorate([
  69931. BABYLON.serialize()
  69932. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  69933. __decorate([
  69934. BABYLON.serialize()
  69935. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  69936. __decorate([
  69937. BABYLON.serialize()
  69938. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  69939. return VolumetricLightScatteringPostProcess;
  69940. }(BABYLON.PostProcess));
  69941. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  69942. })(BABYLON || (BABYLON = {}));
  69943. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  69944. //
  69945. // This post-process allows the modification of rendered colors by using
  69946. // a 'look-up table' (LUT). This effect is also called Color Grading.
  69947. //
  69948. // The object needs to be provided an url to a texture containing the color
  69949. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  69950. // Use an image editing software to tweak the LUT to match your needs.
  69951. //
  69952. // For an example of a color LUT, see here:
  69953. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  69954. // For explanations on color grading, see here:
  69955. // http://udn.epicgames.com/Three/ColorGrading.html
  69956. //
  69957. var BABYLON;
  69958. (function (BABYLON) {
  69959. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  69960. __extends(ColorCorrectionPostProcess, _super);
  69961. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  69962. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  69963. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69964. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  69965. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69966. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69967. _this.onApply = function (effect) {
  69968. effect.setTexture("colorTable", _this._colorTableTexture);
  69969. };
  69970. return _this;
  69971. }
  69972. return ColorCorrectionPostProcess;
  69973. }(BABYLON.PostProcess));
  69974. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  69975. })(BABYLON || (BABYLON = {}));
  69976. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  69977. var BABYLON;
  69978. (function (BABYLON) {
  69979. var TonemappingOperator;
  69980. (function (TonemappingOperator) {
  69981. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  69982. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  69983. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  69984. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  69985. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  69986. ;
  69987. var TonemapPostProcess = /** @class */ (function (_super) {
  69988. __extends(TonemapPostProcess, _super);
  69989. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  69990. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69991. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69992. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  69993. _this._operator = _operator;
  69994. _this.exposureAdjustment = exposureAdjustment;
  69995. var defines = "#define ";
  69996. if (_this._operator === TonemappingOperator.Hable)
  69997. defines += "HABLE_TONEMAPPING";
  69998. else if (_this._operator === TonemappingOperator.Reinhard)
  69999. defines += "REINHARD_TONEMAPPING";
  70000. else if (_this._operator === TonemappingOperator.HejiDawson)
  70001. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  70002. else if (_this._operator === TonemappingOperator.Photographic)
  70003. defines += "PHOTOGRAPHIC_TONEMAPPING";
  70004. //sadly a second call to create the effect.
  70005. _this.updateEffect(defines);
  70006. _this.onApply = function (effect) {
  70007. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  70008. };
  70009. return _this;
  70010. }
  70011. return TonemapPostProcess;
  70012. }(BABYLON.PostProcess));
  70013. BABYLON.TonemapPostProcess = TonemapPostProcess;
  70014. })(BABYLON || (BABYLON = {}));
  70015. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  70016. var BABYLON;
  70017. (function (BABYLON) {
  70018. var DisplayPassPostProcess = /** @class */ (function (_super) {
  70019. __extends(DisplayPassPostProcess, _super);
  70020. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  70021. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  70022. }
  70023. return DisplayPassPostProcess;
  70024. }(BABYLON.PostProcess));
  70025. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  70026. })(BABYLON || (BABYLON = {}));
  70027. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  70028. var BABYLON;
  70029. (function (BABYLON) {
  70030. var HighlightsPostProcess = /** @class */ (function (_super) {
  70031. __extends(HighlightsPostProcess, _super);
  70032. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  70033. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70034. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70035. }
  70036. return HighlightsPostProcess;
  70037. }(BABYLON.PostProcess));
  70038. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  70039. })(BABYLON || (BABYLON = {}));
  70040. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  70041. var BABYLON;
  70042. (function (BABYLON) {
  70043. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  70044. __extends(ImageProcessingPostProcess, _super);
  70045. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  70046. if (camera === void 0) { camera = null; }
  70047. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70048. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  70049. _this._fromLinearSpace = true;
  70050. /**
  70051. * Defines cache preventing GC.
  70052. */
  70053. _this._defines = {
  70054. IMAGEPROCESSING: false,
  70055. VIGNETTE: false,
  70056. VIGNETTEBLENDMODEMULTIPLY: false,
  70057. VIGNETTEBLENDMODEOPAQUE: false,
  70058. TONEMAPPING: false,
  70059. CONTRAST: false,
  70060. COLORCURVES: false,
  70061. COLORGRADING: false,
  70062. COLORGRADING3D: false,
  70063. FROMLINEARSPACE: false,
  70064. SAMPLER3DGREENDEPTH: false,
  70065. SAMPLER3DBGRMAP: false,
  70066. IMAGEPROCESSINGPOSTPROCESS: false,
  70067. EXPOSURE: false,
  70068. GRAIN: false,
  70069. };
  70070. // Setup the configuration as forced by the constructor. This would then not force the
  70071. // scene materials output in linear space and let untouched the default forward pass.
  70072. if (imageProcessingConfiguration) {
  70073. imageProcessingConfiguration.applyByPostProcess = true;
  70074. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  70075. // This will cause the shader to be compiled
  70076. _this.fromLinearSpace = false;
  70077. }
  70078. else {
  70079. _this._attachImageProcessingConfiguration(null, true);
  70080. _this.imageProcessingConfiguration.applyByPostProcess = true;
  70081. }
  70082. _this.onApply = function (effect) {
  70083. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  70084. };
  70085. return _this;
  70086. }
  70087. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  70088. /**
  70089. * Gets the image processing configuration used either in this material.
  70090. */
  70091. get: function () {
  70092. return this._imageProcessingConfiguration;
  70093. },
  70094. /**
  70095. * Sets the Default image processing configuration used either in the this material.
  70096. *
  70097. * If sets to null, the scene one is in use.
  70098. */
  70099. set: function (value) {
  70100. this._attachImageProcessingConfiguration(value);
  70101. },
  70102. enumerable: true,
  70103. configurable: true
  70104. });
  70105. /**
  70106. * Attaches a new image processing configuration to the PBR Material.
  70107. * @param configuration
  70108. */
  70109. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  70110. var _this = this;
  70111. if (doNotBuild === void 0) { doNotBuild = false; }
  70112. if (configuration === this._imageProcessingConfiguration) {
  70113. return;
  70114. }
  70115. // Detaches observer.
  70116. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70117. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70118. }
  70119. // Pick the scene configuration if needed.
  70120. if (!configuration) {
  70121. var scene = null;
  70122. var engine = this.getEngine();
  70123. var camera = this.getCamera();
  70124. if (camera) {
  70125. scene = camera.getScene();
  70126. }
  70127. else if (engine && engine.scenes) {
  70128. var scenes = engine.scenes;
  70129. scene = scenes[scenes.length - 1];
  70130. }
  70131. else {
  70132. scene = BABYLON.Engine.LastCreatedScene;
  70133. }
  70134. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  70135. }
  70136. else {
  70137. this._imageProcessingConfiguration = configuration;
  70138. }
  70139. // Attaches observer.
  70140. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  70141. _this._updateParameters();
  70142. });
  70143. // Ensure the effect will be rebuilt.
  70144. if (!doNotBuild) {
  70145. this._updateParameters();
  70146. }
  70147. };
  70148. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  70149. /**
  70150. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70151. */
  70152. get: function () {
  70153. return this.imageProcessingConfiguration.colorCurves;
  70154. },
  70155. /**
  70156. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70157. */
  70158. set: function (value) {
  70159. this.imageProcessingConfiguration.colorCurves = value;
  70160. },
  70161. enumerable: true,
  70162. configurable: true
  70163. });
  70164. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  70165. /**
  70166. * Gets wether the color curves effect is enabled.
  70167. */
  70168. get: function () {
  70169. return this.imageProcessingConfiguration.colorCurvesEnabled;
  70170. },
  70171. /**
  70172. * Sets wether the color curves effect is enabled.
  70173. */
  70174. set: function (value) {
  70175. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  70176. },
  70177. enumerable: true,
  70178. configurable: true
  70179. });
  70180. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  70181. /**
  70182. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70183. */
  70184. get: function () {
  70185. return this.imageProcessingConfiguration.colorGradingTexture;
  70186. },
  70187. /**
  70188. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70189. */
  70190. set: function (value) {
  70191. this.imageProcessingConfiguration.colorGradingTexture = value;
  70192. },
  70193. enumerable: true,
  70194. configurable: true
  70195. });
  70196. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  70197. /**
  70198. * Gets wether the color grading effect is enabled.
  70199. */
  70200. get: function () {
  70201. return this.imageProcessingConfiguration.colorGradingEnabled;
  70202. },
  70203. /**
  70204. * Gets wether the color grading effect is enabled.
  70205. */
  70206. set: function (value) {
  70207. this.imageProcessingConfiguration.colorGradingEnabled = value;
  70208. },
  70209. enumerable: true,
  70210. configurable: true
  70211. });
  70212. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  70213. /**
  70214. * Gets exposure used in the effect.
  70215. */
  70216. get: function () {
  70217. return this.imageProcessingConfiguration.exposure;
  70218. },
  70219. /**
  70220. * Sets exposure used in the effect.
  70221. */
  70222. set: function (value) {
  70223. this.imageProcessingConfiguration.exposure = value;
  70224. },
  70225. enumerable: true,
  70226. configurable: true
  70227. });
  70228. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  70229. /**
  70230. * Gets wether tonemapping is enabled or not.
  70231. */
  70232. get: function () {
  70233. return this._imageProcessingConfiguration.toneMappingEnabled;
  70234. },
  70235. /**
  70236. * Sets wether tonemapping is enabled or not
  70237. */
  70238. set: function (value) {
  70239. this._imageProcessingConfiguration.toneMappingEnabled = value;
  70240. },
  70241. enumerable: true,
  70242. configurable: true
  70243. });
  70244. ;
  70245. ;
  70246. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  70247. /**
  70248. * Gets contrast used in the effect.
  70249. */
  70250. get: function () {
  70251. return this.imageProcessingConfiguration.contrast;
  70252. },
  70253. /**
  70254. * Sets contrast used in the effect.
  70255. */
  70256. set: function (value) {
  70257. this.imageProcessingConfiguration.contrast = value;
  70258. },
  70259. enumerable: true,
  70260. configurable: true
  70261. });
  70262. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  70263. /**
  70264. * Gets Vignette stretch size.
  70265. */
  70266. get: function () {
  70267. return this.imageProcessingConfiguration.vignetteStretch;
  70268. },
  70269. /**
  70270. * Sets Vignette stretch size.
  70271. */
  70272. set: function (value) {
  70273. this.imageProcessingConfiguration.vignetteStretch = value;
  70274. },
  70275. enumerable: true,
  70276. configurable: true
  70277. });
  70278. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  70279. /**
  70280. * Gets Vignette centre X Offset.
  70281. */
  70282. get: function () {
  70283. return this.imageProcessingConfiguration.vignetteCentreX;
  70284. },
  70285. /**
  70286. * Sets Vignette centre X Offset.
  70287. */
  70288. set: function (value) {
  70289. this.imageProcessingConfiguration.vignetteCentreX = value;
  70290. },
  70291. enumerable: true,
  70292. configurable: true
  70293. });
  70294. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  70295. /**
  70296. * Gets Vignette centre Y Offset.
  70297. */
  70298. get: function () {
  70299. return this.imageProcessingConfiguration.vignetteCentreY;
  70300. },
  70301. /**
  70302. * Sets Vignette centre Y Offset.
  70303. */
  70304. set: function (value) {
  70305. this.imageProcessingConfiguration.vignetteCentreY = value;
  70306. },
  70307. enumerable: true,
  70308. configurable: true
  70309. });
  70310. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  70311. /**
  70312. * Gets Vignette weight or intensity of the vignette effect.
  70313. */
  70314. get: function () {
  70315. return this.imageProcessingConfiguration.vignetteWeight;
  70316. },
  70317. /**
  70318. * Sets Vignette weight or intensity of the vignette effect.
  70319. */
  70320. set: function (value) {
  70321. this.imageProcessingConfiguration.vignetteWeight = value;
  70322. },
  70323. enumerable: true,
  70324. configurable: true
  70325. });
  70326. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  70327. /**
  70328. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70329. * if vignetteEnabled is set to true.
  70330. */
  70331. get: function () {
  70332. return this.imageProcessingConfiguration.vignetteColor;
  70333. },
  70334. /**
  70335. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  70336. * if vignetteEnabled is set to true.
  70337. */
  70338. set: function (value) {
  70339. this.imageProcessingConfiguration.vignetteColor = value;
  70340. },
  70341. enumerable: true,
  70342. configurable: true
  70343. });
  70344. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  70345. /**
  70346. * Gets Camera field of view used by the Vignette effect.
  70347. */
  70348. get: function () {
  70349. return this.imageProcessingConfiguration.vignetteCameraFov;
  70350. },
  70351. /**
  70352. * Sets Camera field of view used by the Vignette effect.
  70353. */
  70354. set: function (value) {
  70355. this.imageProcessingConfiguration.vignetteCameraFov = value;
  70356. },
  70357. enumerable: true,
  70358. configurable: true
  70359. });
  70360. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  70361. /**
  70362. * Gets the vignette blend mode allowing different kind of effect.
  70363. */
  70364. get: function () {
  70365. return this.imageProcessingConfiguration.vignetteBlendMode;
  70366. },
  70367. /**
  70368. * Sets the vignette blend mode allowing different kind of effect.
  70369. */
  70370. set: function (value) {
  70371. this.imageProcessingConfiguration.vignetteBlendMode = value;
  70372. },
  70373. enumerable: true,
  70374. configurable: true
  70375. });
  70376. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  70377. /**
  70378. * Gets wether the vignette effect is enabled.
  70379. */
  70380. get: function () {
  70381. return this.imageProcessingConfiguration.vignetteEnabled;
  70382. },
  70383. /**
  70384. * Sets wether the vignette effect is enabled.
  70385. */
  70386. set: function (value) {
  70387. this.imageProcessingConfiguration.vignetteEnabled = value;
  70388. },
  70389. enumerable: true,
  70390. configurable: true
  70391. });
  70392. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  70393. /**
  70394. * Gets wether the grain effect is enabled.
  70395. */
  70396. get: function () {
  70397. return this.imageProcessingConfiguration.grainEnabled;
  70398. },
  70399. /**
  70400. * Sets wether the grain effect is enabled.
  70401. */
  70402. set: function (value) {
  70403. this.imageProcessingConfiguration.grainEnabled = value;
  70404. },
  70405. enumerable: true,
  70406. configurable: true
  70407. });
  70408. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  70409. /**
  70410. * Gets the grain effect's intensity.
  70411. */
  70412. get: function () {
  70413. return this.imageProcessingConfiguration.grainIntensity;
  70414. },
  70415. /**
  70416. * Sets the grain effect's intensity.
  70417. */
  70418. set: function (value) {
  70419. this.imageProcessingConfiguration.grainIntensity = value;
  70420. },
  70421. enumerable: true,
  70422. configurable: true
  70423. });
  70424. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  70425. /**
  70426. * Gets wether the grain effect is animated.
  70427. */
  70428. get: function () {
  70429. return this.imageProcessingConfiguration.grainAnimated;
  70430. },
  70431. /**
  70432. * Sets wether the grain effect is animated.
  70433. */
  70434. set: function (value) {
  70435. this.imageProcessingConfiguration.grainAnimated = value;
  70436. },
  70437. enumerable: true,
  70438. configurable: true
  70439. });
  70440. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  70441. /**
  70442. * Gets wether the input of the processing is in Gamma or Linear Space.
  70443. */
  70444. get: function () {
  70445. return this._fromLinearSpace;
  70446. },
  70447. /**
  70448. * Sets wether the input of the processing is in Gamma or Linear Space.
  70449. */
  70450. set: function (value) {
  70451. if (this._fromLinearSpace === value) {
  70452. return;
  70453. }
  70454. this._fromLinearSpace = value;
  70455. this._updateParameters();
  70456. },
  70457. enumerable: true,
  70458. configurable: true
  70459. });
  70460. ImageProcessingPostProcess.prototype.getClassName = function () {
  70461. return "ImageProcessingPostProcess";
  70462. };
  70463. ImageProcessingPostProcess.prototype._updateParameters = function () {
  70464. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  70465. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  70466. var defines = "";
  70467. for (var define in this._defines) {
  70468. if (this._defines[define]) {
  70469. defines += "#define " + define + ";\r\n";
  70470. }
  70471. }
  70472. var samplers = ["textureSampler"];
  70473. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  70474. var uniforms = ["scale"];
  70475. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  70476. this.updateEffect(defines, uniforms, samplers);
  70477. };
  70478. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  70479. _super.prototype.dispose.call(this, camera);
  70480. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70481. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70482. }
  70483. this.imageProcessingConfiguration.applyByPostProcess = false;
  70484. };
  70485. __decorate([
  70486. BABYLON.serialize()
  70487. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  70488. return ImageProcessingPostProcess;
  70489. }(BABYLON.PostProcess));
  70490. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  70491. })(BABYLON || (BABYLON = {}));
  70492. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  70493. var BABYLON;
  70494. (function (BABYLON) {
  70495. var Bone = /** @class */ (function (_super) {
  70496. __extends(Bone, _super);
  70497. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  70498. if (parentBone === void 0) { parentBone = null; }
  70499. if (localMatrix === void 0) { localMatrix = null; }
  70500. if (restPose === void 0) { restPose = null; }
  70501. if (baseMatrix === void 0) { baseMatrix = null; }
  70502. if (index === void 0) { index = null; }
  70503. var _this = _super.call(this, name, skeleton.getScene()) || this;
  70504. _this.name = name;
  70505. _this.children = new Array();
  70506. _this.animations = new Array();
  70507. // Set this value to map this bone to a different index in the transform matrices.
  70508. // Set this value to -1 to exclude the bone from the transform matrices.
  70509. _this._index = null;
  70510. _this._worldTransform = new BABYLON.Matrix();
  70511. _this._absoluteTransform = new BABYLON.Matrix();
  70512. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  70513. _this._scaleMatrix = BABYLON.Matrix.Identity();
  70514. _this._scaleVector = BABYLON.Vector3.One();
  70515. _this._negateScaleChildren = BABYLON.Vector3.One();
  70516. _this._scalingDeterminant = 1;
  70517. _this._skeleton = skeleton;
  70518. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  70519. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  70520. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  70521. _this._index = index;
  70522. skeleton.bones.push(_this);
  70523. _this.setParent(parentBone, false);
  70524. _this._updateDifferenceMatrix();
  70525. return _this;
  70526. }
  70527. Object.defineProperty(Bone.prototype, "_matrix", {
  70528. get: function () {
  70529. return this._localMatrix;
  70530. },
  70531. set: function (val) {
  70532. if (this._localMatrix) {
  70533. this._localMatrix.copyFrom(val);
  70534. }
  70535. else {
  70536. this._localMatrix = val;
  70537. }
  70538. },
  70539. enumerable: true,
  70540. configurable: true
  70541. });
  70542. // Members
  70543. Bone.prototype.getSkeleton = function () {
  70544. return this._skeleton;
  70545. };
  70546. Bone.prototype.getParent = function () {
  70547. return this._parent;
  70548. };
  70549. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  70550. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70551. if (this._parent === parent) {
  70552. return;
  70553. }
  70554. if (this._parent) {
  70555. var index = this._parent.children.indexOf(this);
  70556. if (index !== -1) {
  70557. this._parent.children.splice(index, 1);
  70558. }
  70559. }
  70560. this._parent = parent;
  70561. if (this._parent) {
  70562. this._parent.children.push(this);
  70563. }
  70564. if (updateDifferenceMatrix) {
  70565. this._updateDifferenceMatrix();
  70566. }
  70567. };
  70568. Bone.prototype.getLocalMatrix = function () {
  70569. return this._localMatrix;
  70570. };
  70571. Bone.prototype.getBaseMatrix = function () {
  70572. return this._baseMatrix;
  70573. };
  70574. Bone.prototype.getRestPose = function () {
  70575. return this._restPose;
  70576. };
  70577. Bone.prototype.returnToRest = function () {
  70578. this.updateMatrix(this._restPose.clone());
  70579. };
  70580. Bone.prototype.getWorldMatrix = function () {
  70581. return this._worldTransform;
  70582. };
  70583. Bone.prototype.getInvertedAbsoluteTransform = function () {
  70584. return this._invertedAbsoluteTransform;
  70585. };
  70586. Bone.prototype.getAbsoluteTransform = function () {
  70587. return this._absoluteTransform;
  70588. };
  70589. Object.defineProperty(Bone.prototype, "position", {
  70590. // Properties (matches AbstractMesh properties)
  70591. get: function () {
  70592. return this.getPosition();
  70593. },
  70594. set: function (newPosition) {
  70595. this.setPosition(newPosition);
  70596. },
  70597. enumerable: true,
  70598. configurable: true
  70599. });
  70600. Object.defineProperty(Bone.prototype, "rotation", {
  70601. get: function () {
  70602. return this.getRotation();
  70603. },
  70604. set: function (newRotation) {
  70605. this.setRotation(newRotation);
  70606. },
  70607. enumerable: true,
  70608. configurable: true
  70609. });
  70610. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  70611. get: function () {
  70612. return this.getRotationQuaternion();
  70613. },
  70614. set: function (newRotation) {
  70615. this.setRotationQuaternion(newRotation);
  70616. },
  70617. enumerable: true,
  70618. configurable: true
  70619. });
  70620. Object.defineProperty(Bone.prototype, "scaling", {
  70621. get: function () {
  70622. return this.getScale();
  70623. },
  70624. set: function (newScaling) {
  70625. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  70626. },
  70627. enumerable: true,
  70628. configurable: true
  70629. });
  70630. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  70631. /**
  70632. * Gets the animation properties override
  70633. */
  70634. get: function () {
  70635. return this._skeleton.animationPropertiesOverride;
  70636. },
  70637. enumerable: true,
  70638. configurable: true
  70639. });
  70640. // Methods
  70641. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  70642. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70643. this._baseMatrix = matrix.clone();
  70644. this._localMatrix = matrix.clone();
  70645. this._skeleton._markAsDirty();
  70646. if (updateDifferenceMatrix) {
  70647. this._updateDifferenceMatrix();
  70648. }
  70649. };
  70650. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  70651. if (!rootMatrix) {
  70652. rootMatrix = this._baseMatrix;
  70653. }
  70654. if (this._parent) {
  70655. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70656. }
  70657. else {
  70658. this._absoluteTransform.copyFrom(rootMatrix);
  70659. }
  70660. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  70661. for (var index = 0; index < this.children.length; index++) {
  70662. this.children[index]._updateDifferenceMatrix();
  70663. }
  70664. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  70665. };
  70666. Bone.prototype.markAsDirty = function () {
  70667. this._currentRenderId++;
  70668. this._skeleton._markAsDirty();
  70669. };
  70670. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  70671. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70672. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  70673. // all animation may be coming from a library skeleton, so may need to create animation
  70674. if (this.animations.length === 0) {
  70675. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  70676. this.animations[0].setKeys([]);
  70677. }
  70678. // get animation info / verify there is such a range from the source bone
  70679. var sourceRange = source.animations[0].getRange(rangeName);
  70680. if (!sourceRange) {
  70681. return false;
  70682. }
  70683. var from = sourceRange.from;
  70684. var to = sourceRange.to;
  70685. var sourceKeys = source.animations[0].getKeys();
  70686. // rescaling prep
  70687. var sourceBoneLength = source.length;
  70688. var sourceParent = source.getParent();
  70689. var parent = this.getParent();
  70690. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  70691. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  70692. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  70693. var destKeys = this.animations[0].getKeys();
  70694. // loop vars declaration
  70695. var orig;
  70696. var origTranslation;
  70697. var mat;
  70698. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  70699. orig = sourceKeys[key];
  70700. if (orig.frame >= from && orig.frame <= to) {
  70701. if (rescaleAsRequired) {
  70702. mat = orig.value.clone();
  70703. // scale based on parent ratio, when bone has parent
  70704. if (parentScalingReqd) {
  70705. origTranslation = mat.getTranslation();
  70706. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  70707. // scale based on skeleton dimension ratio when root bone, and value is passed
  70708. }
  70709. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  70710. origTranslation = mat.getTranslation();
  70711. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  70712. // use original when root bone, and no data for skelDimensionsRatio
  70713. }
  70714. else {
  70715. mat = orig.value;
  70716. }
  70717. }
  70718. else {
  70719. mat = orig.value;
  70720. }
  70721. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  70722. }
  70723. }
  70724. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  70725. return true;
  70726. };
  70727. /**
  70728. * Translate the bone in local or world space.
  70729. * @param vec The amount to translate the bone.
  70730. * @param space The space that the translation is in.
  70731. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70732. */
  70733. Bone.prototype.translate = function (vec, space, mesh) {
  70734. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70735. var lm = this.getLocalMatrix();
  70736. if (space == BABYLON.Space.LOCAL) {
  70737. lm.m[12] += vec.x;
  70738. lm.m[13] += vec.y;
  70739. lm.m[14] += vec.z;
  70740. }
  70741. else {
  70742. var wm = null;
  70743. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70744. if (mesh) {
  70745. wm = mesh.getWorldMatrix();
  70746. }
  70747. this._skeleton.computeAbsoluteTransforms();
  70748. var tmat = Bone._tmpMats[0];
  70749. var tvec = Bone._tmpVecs[0];
  70750. if (this._parent) {
  70751. if (mesh && wm) {
  70752. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70753. tmat.multiplyToRef(wm, tmat);
  70754. }
  70755. else {
  70756. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70757. }
  70758. }
  70759. tmat.m[12] = 0;
  70760. tmat.m[13] = 0;
  70761. tmat.m[14] = 0;
  70762. tmat.invert();
  70763. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  70764. lm.m[12] += tvec.x;
  70765. lm.m[13] += tvec.y;
  70766. lm.m[14] += tvec.z;
  70767. }
  70768. this.markAsDirty();
  70769. };
  70770. /**
  70771. * Set the postion of the bone in local or world space.
  70772. * @param position The position to set the bone.
  70773. * @param space The space that the position is in.
  70774. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70775. */
  70776. Bone.prototype.setPosition = function (position, space, mesh) {
  70777. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70778. var lm = this.getLocalMatrix();
  70779. if (space == BABYLON.Space.LOCAL) {
  70780. lm.m[12] = position.x;
  70781. lm.m[13] = position.y;
  70782. lm.m[14] = position.z;
  70783. }
  70784. else {
  70785. var wm = null;
  70786. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70787. if (mesh) {
  70788. wm = mesh.getWorldMatrix();
  70789. }
  70790. this._skeleton.computeAbsoluteTransforms();
  70791. var tmat = Bone._tmpMats[0];
  70792. var vec = Bone._tmpVecs[0];
  70793. if (this._parent) {
  70794. if (mesh && wm) {
  70795. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70796. tmat.multiplyToRef(wm, tmat);
  70797. }
  70798. else {
  70799. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70800. }
  70801. }
  70802. tmat.invert();
  70803. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  70804. lm.m[12] = vec.x;
  70805. lm.m[13] = vec.y;
  70806. lm.m[14] = vec.z;
  70807. }
  70808. this.markAsDirty();
  70809. };
  70810. /**
  70811. * Set the absolute postion of the bone (world space).
  70812. * @param position The position to set the bone.
  70813. * @param mesh The mesh that this bone is attached to.
  70814. */
  70815. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  70816. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  70817. };
  70818. /**
  70819. * Set the scale of the bone on the x, y and z axes.
  70820. * @param x The scale of the bone on the x axis.
  70821. * @param x The scale of the bone on the y axis.
  70822. * @param z The scale of the bone on the z axis.
  70823. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70824. */
  70825. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  70826. if (scaleChildren === void 0) { scaleChildren = false; }
  70827. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  70828. if (!scaleChildren) {
  70829. this._negateScaleChildren.x = 1 / x;
  70830. this._negateScaleChildren.y = 1 / y;
  70831. this._negateScaleChildren.z = 1 / z;
  70832. }
  70833. this._syncScaleVector();
  70834. }
  70835. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  70836. };
  70837. /**
  70838. * Scale the bone on the x, y and z axes.
  70839. * @param x The amount to scale the bone on the x axis.
  70840. * @param x The amount to scale the bone on the y axis.
  70841. * @param z The amount to scale the bone on the z axis.
  70842. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70843. */
  70844. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  70845. if (scaleChildren === void 0) { scaleChildren = false; }
  70846. var locMat = this.getLocalMatrix();
  70847. var origLocMat = Bone._tmpMats[0];
  70848. origLocMat.copyFrom(locMat);
  70849. var origLocMatInv = Bone._tmpMats[1];
  70850. origLocMatInv.copyFrom(origLocMat);
  70851. origLocMatInv.invert();
  70852. var scaleMat = Bone._tmpMats[2];
  70853. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  70854. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  70855. this._scaleVector.x *= x;
  70856. this._scaleVector.y *= y;
  70857. this._scaleVector.z *= z;
  70858. locMat.multiplyToRef(origLocMatInv, locMat);
  70859. locMat.multiplyToRef(scaleMat, locMat);
  70860. locMat.multiplyToRef(origLocMat, locMat);
  70861. var parent = this.getParent();
  70862. if (parent) {
  70863. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  70864. }
  70865. else {
  70866. this.getAbsoluteTransform().copyFrom(locMat);
  70867. }
  70868. var len = this.children.length;
  70869. scaleMat.invert();
  70870. for (var i = 0; i < len; i++) {
  70871. var child = this.children[i];
  70872. var cm = child.getLocalMatrix();
  70873. cm.multiplyToRef(scaleMat, cm);
  70874. var lm = child.getLocalMatrix();
  70875. lm.m[12] *= x;
  70876. lm.m[13] *= y;
  70877. lm.m[14] *= z;
  70878. }
  70879. this.computeAbsoluteTransforms();
  70880. if (scaleChildren) {
  70881. for (var i = 0; i < len; i++) {
  70882. this.children[i].scale(x, y, z, scaleChildren);
  70883. }
  70884. }
  70885. this.markAsDirty();
  70886. };
  70887. /**
  70888. * Set the yaw, pitch, and roll of the bone in local or world space.
  70889. * @param yaw The rotation of the bone on the y axis.
  70890. * @param pitch The rotation of the bone on the x axis.
  70891. * @param roll The rotation of the bone on the z axis.
  70892. * @param space The space that the axes of rotation are in.
  70893. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70894. */
  70895. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  70896. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70897. var rotMat = Bone._tmpMats[0];
  70898. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  70899. var rotMatInv = Bone._tmpMats[1];
  70900. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70901. rotMatInv.multiplyToRef(rotMat, rotMat);
  70902. this._rotateWithMatrix(rotMat, space, mesh);
  70903. };
  70904. /**
  70905. * Rotate the bone on an axis in local or world space.
  70906. * @param axis The axis to rotate the bone on.
  70907. * @param amount The amount to rotate the bone.
  70908. * @param space The space that the axis is in.
  70909. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70910. */
  70911. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  70912. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70913. var rmat = Bone._tmpMats[0];
  70914. rmat.m[12] = 0;
  70915. rmat.m[13] = 0;
  70916. rmat.m[14] = 0;
  70917. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  70918. this._rotateWithMatrix(rmat, space, mesh);
  70919. };
  70920. /**
  70921. * Set the rotation of the bone to a particular axis angle in local or world space.
  70922. * @param axis The axis to rotate the bone on.
  70923. * @param angle The angle that the bone should be rotated to.
  70924. * @param space The space that the axis is in.
  70925. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70926. */
  70927. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  70928. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70929. var rotMat = Bone._tmpMats[0];
  70930. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  70931. var rotMatInv = Bone._tmpMats[1];
  70932. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70933. rotMatInv.multiplyToRef(rotMat, rotMat);
  70934. this._rotateWithMatrix(rotMat, space, mesh);
  70935. };
  70936. /**
  70937. * Set the euler rotation of the bone in local of world space.
  70938. * @param rotation The euler rotation that the bone should be set to.
  70939. * @param space The space that the rotation is in.
  70940. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70941. */
  70942. Bone.prototype.setRotation = function (rotation, space, mesh) {
  70943. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70944. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  70945. };
  70946. /**
  70947. * Set the quaternion rotation of the bone in local of world space.
  70948. * @param quat The quaternion rotation that the bone should be set to.
  70949. * @param space The space that the rotation is in.
  70950. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70951. */
  70952. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  70953. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70954. var rotMatInv = Bone._tmpMats[0];
  70955. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70956. var rotMat = Bone._tmpMats[1];
  70957. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  70958. rotMatInv.multiplyToRef(rotMat, rotMat);
  70959. this._rotateWithMatrix(rotMat, space, mesh);
  70960. };
  70961. /**
  70962. * Set the rotation matrix of the bone in local of world space.
  70963. * @param rotMat The rotation matrix that the bone should be set to.
  70964. * @param space The space that the rotation is in.
  70965. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70966. */
  70967. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  70968. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70969. var rotMatInv = Bone._tmpMats[0];
  70970. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70971. var rotMat2 = Bone._tmpMats[1];
  70972. rotMat2.copyFrom(rotMat);
  70973. rotMatInv.multiplyToRef(rotMat, rotMat2);
  70974. this._rotateWithMatrix(rotMat2, space, mesh);
  70975. };
  70976. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  70977. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70978. var lmat = this.getLocalMatrix();
  70979. var lx = lmat.m[12];
  70980. var ly = lmat.m[13];
  70981. var lz = lmat.m[14];
  70982. var parent = this.getParent();
  70983. var parentScale = Bone._tmpMats[3];
  70984. var parentScaleInv = Bone._tmpMats[4];
  70985. if (parent) {
  70986. if (space == BABYLON.Space.WORLD) {
  70987. if (mesh) {
  70988. parentScale.copyFrom(mesh.getWorldMatrix());
  70989. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  70990. }
  70991. else {
  70992. parentScale.copyFrom(parent.getAbsoluteTransform());
  70993. }
  70994. }
  70995. else {
  70996. parentScale = parent._scaleMatrix;
  70997. }
  70998. parentScaleInv.copyFrom(parentScale);
  70999. parentScaleInv.invert();
  71000. lmat.multiplyToRef(parentScale, lmat);
  71001. lmat.multiplyToRef(rmat, lmat);
  71002. lmat.multiplyToRef(parentScaleInv, lmat);
  71003. }
  71004. else {
  71005. if (space == BABYLON.Space.WORLD && mesh) {
  71006. parentScale.copyFrom(mesh.getWorldMatrix());
  71007. parentScaleInv.copyFrom(parentScale);
  71008. parentScaleInv.invert();
  71009. lmat.multiplyToRef(parentScale, lmat);
  71010. lmat.multiplyToRef(rmat, lmat);
  71011. lmat.multiplyToRef(parentScaleInv, lmat);
  71012. }
  71013. else {
  71014. lmat.multiplyToRef(rmat, lmat);
  71015. }
  71016. }
  71017. lmat.m[12] = lx;
  71018. lmat.m[13] = ly;
  71019. lmat.m[14] = lz;
  71020. this.computeAbsoluteTransforms();
  71021. this.markAsDirty();
  71022. };
  71023. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  71024. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71025. if (space == BABYLON.Space.WORLD) {
  71026. var scaleMatrix = Bone._tmpMats[2];
  71027. scaleMatrix.copyFrom(this._scaleMatrix);
  71028. rotMatInv.copyFrom(this.getAbsoluteTransform());
  71029. if (mesh) {
  71030. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  71031. var meshScale = Bone._tmpMats[3];
  71032. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  71033. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  71034. }
  71035. rotMatInv.invert();
  71036. scaleMatrix.m[0] *= this._scalingDeterminant;
  71037. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71038. }
  71039. else {
  71040. rotMatInv.copyFrom(this.getLocalMatrix());
  71041. rotMatInv.invert();
  71042. var scaleMatrix = Bone._tmpMats[2];
  71043. scaleMatrix.copyFrom(this._scaleMatrix);
  71044. if (this._parent) {
  71045. var pscaleMatrix = Bone._tmpMats[3];
  71046. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  71047. pscaleMatrix.invert();
  71048. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  71049. }
  71050. else {
  71051. scaleMatrix.m[0] *= this._scalingDeterminant;
  71052. }
  71053. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71054. }
  71055. };
  71056. /**
  71057. * Get the scale of the bone
  71058. * @returns the scale of the bone
  71059. */
  71060. Bone.prototype.getScale = function () {
  71061. return this._scaleVector.clone();
  71062. };
  71063. /**
  71064. * Copy the scale of the bone to a vector3.
  71065. * @param result The vector3 to copy the scale to
  71066. */
  71067. Bone.prototype.getScaleToRef = function (result) {
  71068. result.copyFrom(this._scaleVector);
  71069. };
  71070. /**
  71071. * Get the position of the bone in local or world space.
  71072. * @param space The space that the returned position is in.
  71073. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71074. * @returns The position of the bone
  71075. */
  71076. Bone.prototype.getPosition = function (space, mesh) {
  71077. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71078. if (mesh === void 0) { mesh = null; }
  71079. var pos = BABYLON.Vector3.Zero();
  71080. this.getPositionToRef(space, mesh, pos);
  71081. return pos;
  71082. };
  71083. /**
  71084. * Copy the position of the bone to a vector3 in local or world space.
  71085. * @param space The space that the returned position is in.
  71086. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71087. * @param result The vector3 to copy the position to.
  71088. */
  71089. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  71090. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71091. if (space == BABYLON.Space.LOCAL) {
  71092. var lm = this.getLocalMatrix();
  71093. result.x = lm.m[12];
  71094. result.y = lm.m[13];
  71095. result.z = lm.m[14];
  71096. }
  71097. else {
  71098. var wm = null;
  71099. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71100. if (mesh) {
  71101. wm = mesh.getWorldMatrix();
  71102. }
  71103. this._skeleton.computeAbsoluteTransforms();
  71104. var tmat = Bone._tmpMats[0];
  71105. if (mesh && wm) {
  71106. tmat.copyFrom(this.getAbsoluteTransform());
  71107. tmat.multiplyToRef(wm, tmat);
  71108. }
  71109. else {
  71110. tmat = this.getAbsoluteTransform();
  71111. }
  71112. result.x = tmat.m[12];
  71113. result.y = tmat.m[13];
  71114. result.z = tmat.m[14];
  71115. }
  71116. };
  71117. /**
  71118. * Get the absolute position of the bone (world space).
  71119. * @param mesh The mesh that this bone is attached to.
  71120. * @returns The absolute position of the bone
  71121. */
  71122. Bone.prototype.getAbsolutePosition = function (mesh) {
  71123. if (mesh === void 0) { mesh = null; }
  71124. var pos = BABYLON.Vector3.Zero();
  71125. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  71126. return pos;
  71127. };
  71128. /**
  71129. * Copy the absolute position of the bone (world space) to the result param.
  71130. * @param mesh The mesh that this bone is attached to.
  71131. * @param result The vector3 to copy the absolute position to.
  71132. */
  71133. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  71134. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  71135. };
  71136. /**
  71137. * Compute the absolute transforms of this bone and its children.
  71138. */
  71139. Bone.prototype.computeAbsoluteTransforms = function () {
  71140. if (this._parent) {
  71141. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71142. }
  71143. else {
  71144. this._absoluteTransform.copyFrom(this._localMatrix);
  71145. var poseMatrix = this._skeleton.getPoseMatrix();
  71146. if (poseMatrix) {
  71147. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  71148. }
  71149. }
  71150. var children = this.children;
  71151. var len = children.length;
  71152. for (var i = 0; i < len; i++) {
  71153. children[i].computeAbsoluteTransforms();
  71154. }
  71155. };
  71156. Bone.prototype._syncScaleVector = function () {
  71157. var lm = this.getLocalMatrix();
  71158. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  71159. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  71160. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  71161. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  71162. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  71163. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  71164. this._scaleVector.x = xs * Math.sqrt(xsq);
  71165. this._scaleVector.y = ys * Math.sqrt(ysq);
  71166. this._scaleVector.z = zs * Math.sqrt(zsq);
  71167. if (this._parent) {
  71168. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  71169. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  71170. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  71171. }
  71172. 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);
  71173. };
  71174. /**
  71175. * Get the world direction from an axis that is in the local space of the bone.
  71176. * @param localAxis The local direction that is used to compute the world direction.
  71177. * @param mesh The mesh that this bone is attached to.
  71178. * @returns The world direction
  71179. */
  71180. Bone.prototype.getDirection = function (localAxis, mesh) {
  71181. if (mesh === void 0) { mesh = null; }
  71182. var result = BABYLON.Vector3.Zero();
  71183. this.getDirectionToRef(localAxis, mesh, result);
  71184. return result;
  71185. };
  71186. /**
  71187. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  71188. * @param localAxis The local direction that is used to compute the world direction.
  71189. * @param mesh The mesh that this bone is attached to.
  71190. * @param result The vector3 that the world direction will be copied to.
  71191. */
  71192. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  71193. if (mesh === void 0) { mesh = null; }
  71194. var wm = null;
  71195. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71196. if (mesh) {
  71197. wm = mesh.getWorldMatrix();
  71198. }
  71199. this._skeleton.computeAbsoluteTransforms();
  71200. var mat = Bone._tmpMats[0];
  71201. mat.copyFrom(this.getAbsoluteTransform());
  71202. if (mesh && wm) {
  71203. mat.multiplyToRef(wm, mat);
  71204. }
  71205. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  71206. result.normalize();
  71207. };
  71208. /**
  71209. * Get the euler rotation of the bone in local or world space.
  71210. * @param space The space that the rotation should be in.
  71211. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71212. * @returns The euler rotation
  71213. */
  71214. Bone.prototype.getRotation = function (space, mesh) {
  71215. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71216. if (mesh === void 0) { mesh = null; }
  71217. var result = BABYLON.Vector3.Zero();
  71218. this.getRotationToRef(space, mesh, result);
  71219. return result;
  71220. };
  71221. /**
  71222. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  71223. * @param space The space that the rotation should be in.
  71224. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71225. * @param result The vector3 that the rotation should be copied to.
  71226. */
  71227. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  71228. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71229. if (mesh === void 0) { mesh = null; }
  71230. var quat = Bone._tmpQuat;
  71231. this.getRotationQuaternionToRef(space, mesh, quat);
  71232. quat.toEulerAnglesToRef(result);
  71233. };
  71234. /**
  71235. * Get the quaternion rotation of the bone in either local or world space.
  71236. * @param space The space that the rotation should be in.
  71237. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71238. * @returns The quaternion rotation
  71239. */
  71240. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  71241. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71242. if (mesh === void 0) { mesh = null; }
  71243. var result = BABYLON.Quaternion.Identity();
  71244. this.getRotationQuaternionToRef(space, mesh, result);
  71245. return result;
  71246. };
  71247. /**
  71248. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  71249. * @param space The space that the rotation should be in.
  71250. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71251. * @param result The quaternion that the rotation should be copied to.
  71252. */
  71253. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  71254. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71255. if (mesh === void 0) { mesh = null; }
  71256. if (space == BABYLON.Space.LOCAL) {
  71257. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71258. }
  71259. else {
  71260. var mat = Bone._tmpMats[0];
  71261. var amat = this.getAbsoluteTransform();
  71262. if (mesh) {
  71263. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71264. }
  71265. else {
  71266. mat.copyFrom(amat);
  71267. }
  71268. mat.m[0] *= this._scalingDeterminant;
  71269. mat.m[1] *= this._scalingDeterminant;
  71270. mat.m[2] *= this._scalingDeterminant;
  71271. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  71272. }
  71273. };
  71274. /**
  71275. * Get the rotation matrix of the bone in local or world space.
  71276. * @param space The space that the rotation should be in.
  71277. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71278. * @returns The rotation matrix
  71279. */
  71280. Bone.prototype.getRotationMatrix = function (space, mesh) {
  71281. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71282. var result = BABYLON.Matrix.Identity();
  71283. this.getRotationMatrixToRef(space, mesh, result);
  71284. return result;
  71285. };
  71286. /**
  71287. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  71288. * @param space The space that the rotation should be in.
  71289. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71290. * @param result The quaternion that the rotation should be copied to.
  71291. */
  71292. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  71293. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71294. if (space == BABYLON.Space.LOCAL) {
  71295. this.getLocalMatrix().getRotationMatrixToRef(result);
  71296. }
  71297. else {
  71298. var mat = Bone._tmpMats[0];
  71299. var amat = this.getAbsoluteTransform();
  71300. if (mesh) {
  71301. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  71302. }
  71303. else {
  71304. mat.copyFrom(amat);
  71305. }
  71306. mat.m[0] *= this._scalingDeterminant;
  71307. mat.m[1] *= this._scalingDeterminant;
  71308. mat.m[2] *= this._scalingDeterminant;
  71309. mat.getRotationMatrixToRef(result);
  71310. }
  71311. };
  71312. /**
  71313. * Get the world position of a point that is in the local space of the bone.
  71314. * @param position The local position
  71315. * @param mesh The mesh that this bone is attached to.
  71316. * @returns The world position
  71317. */
  71318. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  71319. if (mesh === void 0) { mesh = null; }
  71320. var result = BABYLON.Vector3.Zero();
  71321. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  71322. return result;
  71323. };
  71324. /**
  71325. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  71326. * @param position The local position
  71327. * @param mesh The mesh that this bone is attached to.
  71328. * @param result The vector3 that the world position should be copied to.
  71329. */
  71330. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  71331. if (mesh === void 0) { mesh = null; }
  71332. var wm = null;
  71333. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71334. if (mesh) {
  71335. wm = mesh.getWorldMatrix();
  71336. }
  71337. this._skeleton.computeAbsoluteTransforms();
  71338. var tmat = Bone._tmpMats[0];
  71339. if (mesh && wm) {
  71340. tmat.copyFrom(this.getAbsoluteTransform());
  71341. tmat.multiplyToRef(wm, tmat);
  71342. }
  71343. else {
  71344. tmat = this.getAbsoluteTransform();
  71345. }
  71346. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71347. };
  71348. /**
  71349. * Get the local position of a point that is in world space.
  71350. * @param position The world position
  71351. * @param mesh The mesh that this bone is attached to.
  71352. * @returns The local position
  71353. */
  71354. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  71355. if (mesh === void 0) { mesh = null; }
  71356. var result = BABYLON.Vector3.Zero();
  71357. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  71358. return result;
  71359. };
  71360. /**
  71361. * Get the local position of a point that is in world space and copy it to the result param.
  71362. * @param position The world position
  71363. * @param mesh The mesh that this bone is attached to.
  71364. * @param result The vector3 that the local position should be copied to.
  71365. */
  71366. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  71367. if (mesh === void 0) { mesh = null; }
  71368. var wm = null;
  71369. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71370. if (mesh) {
  71371. wm = mesh.getWorldMatrix();
  71372. }
  71373. this._skeleton.computeAbsoluteTransforms();
  71374. var tmat = Bone._tmpMats[0];
  71375. tmat.copyFrom(this.getAbsoluteTransform());
  71376. if (mesh && wm) {
  71377. tmat.multiplyToRef(wm, tmat);
  71378. }
  71379. tmat.invert();
  71380. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  71381. };
  71382. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71383. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  71384. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71385. return Bone;
  71386. }(BABYLON.Node));
  71387. BABYLON.Bone = Bone;
  71388. })(BABYLON || (BABYLON = {}));
  71389. //# sourceMappingURL=babylon.bone.js.map
  71390. var BABYLON;
  71391. (function (BABYLON) {
  71392. var BoneIKController = /** @class */ (function () {
  71393. function BoneIKController(mesh, bone, options) {
  71394. this.targetPosition = BABYLON.Vector3.Zero();
  71395. this.poleTargetPosition = BABYLON.Vector3.Zero();
  71396. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  71397. this.poleAngle = 0;
  71398. this.slerpAmount = 1;
  71399. this._bone1Quat = BABYLON.Quaternion.Identity();
  71400. this._bone1Mat = BABYLON.Matrix.Identity();
  71401. this._bone2Ang = Math.PI;
  71402. this._maxAngle = Math.PI;
  71403. this._rightHandedSystem = false;
  71404. this._bendAxis = BABYLON.Vector3.Right();
  71405. this._slerping = false;
  71406. this._adjustRoll = 0;
  71407. this._bone2 = bone;
  71408. this._bone1 = bone.getParent();
  71409. if (!this._bone1) {
  71410. return;
  71411. }
  71412. this.mesh = mesh;
  71413. var bonePos = bone.getPosition();
  71414. if (bone.getAbsoluteTransform().determinant() > 0) {
  71415. this._rightHandedSystem = true;
  71416. this._bendAxis.x = 0;
  71417. this._bendAxis.y = 0;
  71418. this._bendAxis.z = -1;
  71419. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  71420. this._adjustRoll = Math.PI * .5;
  71421. this._bendAxis.z = 1;
  71422. }
  71423. }
  71424. if (this._bone1.length) {
  71425. var boneScale1 = this._bone1.getScale();
  71426. var boneScale2 = this._bone2.getScale();
  71427. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  71428. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  71429. }
  71430. else if (this._bone1.children[0]) {
  71431. mesh.computeWorldMatrix(true);
  71432. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  71433. var pos2 = this._bone2.getAbsolutePosition(mesh);
  71434. var pos3 = this._bone1.getAbsolutePosition(mesh);
  71435. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  71436. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  71437. }
  71438. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  71439. this.maxAngle = Math.PI;
  71440. if (options) {
  71441. if (options.targetMesh) {
  71442. this.targetMesh = options.targetMesh;
  71443. this.targetMesh.computeWorldMatrix(true);
  71444. }
  71445. if (options.poleTargetMesh) {
  71446. this.poleTargetMesh = options.poleTargetMesh;
  71447. this.poleTargetMesh.computeWorldMatrix(true);
  71448. }
  71449. else if (options.poleTargetBone) {
  71450. this.poleTargetBone = options.poleTargetBone;
  71451. }
  71452. else if (this._bone1.getParent()) {
  71453. this.poleTargetBone = this._bone1.getParent();
  71454. }
  71455. if (options.poleTargetLocalOffset) {
  71456. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  71457. }
  71458. if (options.poleAngle) {
  71459. this.poleAngle = options.poleAngle;
  71460. }
  71461. if (options.bendAxis) {
  71462. this._bendAxis.copyFrom(options.bendAxis);
  71463. }
  71464. if (options.maxAngle) {
  71465. this.maxAngle = options.maxAngle;
  71466. }
  71467. if (options.slerpAmount) {
  71468. this.slerpAmount = options.slerpAmount;
  71469. }
  71470. }
  71471. }
  71472. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  71473. get: function () {
  71474. return this._maxAngle;
  71475. },
  71476. set: function (value) {
  71477. this._setMaxAngle(value);
  71478. },
  71479. enumerable: true,
  71480. configurable: true
  71481. });
  71482. BoneIKController.prototype._setMaxAngle = function (ang) {
  71483. if (ang < 0) {
  71484. ang = 0;
  71485. }
  71486. if (ang > Math.PI || ang == undefined) {
  71487. ang = Math.PI;
  71488. }
  71489. this._maxAngle = ang;
  71490. var a = this._bone1Length;
  71491. var b = this._bone2Length;
  71492. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  71493. };
  71494. BoneIKController.prototype.update = function () {
  71495. var bone1 = this._bone1;
  71496. if (!bone1) {
  71497. return;
  71498. }
  71499. var target = this.targetPosition;
  71500. var poleTarget = this.poleTargetPosition;
  71501. var mat1 = BoneIKController._tmpMats[0];
  71502. var mat2 = BoneIKController._tmpMats[1];
  71503. if (this.targetMesh) {
  71504. target.copyFrom(this.targetMesh.getAbsolutePosition());
  71505. }
  71506. if (this.poleTargetBone) {
  71507. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  71508. }
  71509. else if (this.poleTargetMesh) {
  71510. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  71511. }
  71512. var bonePos = BoneIKController._tmpVecs[0];
  71513. var zaxis = BoneIKController._tmpVecs[1];
  71514. var xaxis = BoneIKController._tmpVecs[2];
  71515. var yaxis = BoneIKController._tmpVecs[3];
  71516. var upAxis = BoneIKController._tmpVecs[4];
  71517. var _tmpQuat = BoneIKController._tmpQuat;
  71518. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  71519. poleTarget.subtractToRef(bonePos, upAxis);
  71520. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  71521. upAxis.y = 1;
  71522. }
  71523. else {
  71524. upAxis.normalize();
  71525. }
  71526. target.subtractToRef(bonePos, yaxis);
  71527. yaxis.normalize();
  71528. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  71529. zaxis.normalize();
  71530. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  71531. xaxis.normalize();
  71532. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  71533. var a = this._bone1Length;
  71534. var b = this._bone2Length;
  71535. var c = BABYLON.Vector3.Distance(bonePos, target);
  71536. if (this._maxReach > 0) {
  71537. c = Math.min(this._maxReach, c);
  71538. }
  71539. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  71540. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  71541. if (acosa > 1) {
  71542. acosa = 1;
  71543. }
  71544. if (acosb > 1) {
  71545. acosb = 1;
  71546. }
  71547. if (acosa < -1) {
  71548. acosa = -1;
  71549. }
  71550. if (acosb < -1) {
  71551. acosb = -1;
  71552. }
  71553. var angA = Math.acos(acosa);
  71554. var angB = Math.acos(acosb);
  71555. var angC = -angA - angB;
  71556. if (this._rightHandedSystem) {
  71557. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  71558. mat2.multiplyToRef(mat1, mat1);
  71559. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  71560. mat2.multiplyToRef(mat1, mat1);
  71561. }
  71562. else {
  71563. var _tmpVec = BoneIKController._tmpVecs[5];
  71564. _tmpVec.copyFrom(this._bendAxis);
  71565. _tmpVec.x *= -1;
  71566. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  71567. mat2.multiplyToRef(mat1, mat1);
  71568. }
  71569. if (this.poleAngle) {
  71570. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  71571. mat1.multiplyToRef(mat2, mat1);
  71572. }
  71573. if (this._bone1) {
  71574. if (this.slerpAmount < 1) {
  71575. if (!this._slerping) {
  71576. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  71577. }
  71578. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  71579. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  71580. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  71581. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  71582. this._slerping = true;
  71583. }
  71584. else {
  71585. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  71586. this._bone1Mat.copyFrom(mat1);
  71587. this._slerping = false;
  71588. }
  71589. }
  71590. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  71591. this._bone2Ang = angC;
  71592. };
  71593. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71594. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  71595. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71596. return BoneIKController;
  71597. }());
  71598. BABYLON.BoneIKController = BoneIKController;
  71599. })(BABYLON || (BABYLON = {}));
  71600. //# sourceMappingURL=babylon.boneIKController.js.map
  71601. var BABYLON;
  71602. (function (BABYLON) {
  71603. var BoneLookController = /** @class */ (function () {
  71604. /**
  71605. * Create a BoneLookController
  71606. * @param mesh the mesh that the bone belongs to
  71607. * @param bone the bone that will be looking to the target
  71608. * @param target the target Vector3 to look at
  71609. * @param settings optional settings:
  71610. * - maxYaw: the maximum angle the bone will yaw to
  71611. * - minYaw: the minimum angle the bone will yaw to
  71612. * - maxPitch: the maximum angle the bone will pitch to
  71613. * - minPitch: the minimum angle the bone will yaw to
  71614. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  71615. * - upAxis: the up axis of the coordinate system
  71616. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71617. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  71618. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  71619. * - adjustYaw: used to make an adjustment to the yaw of the bone
  71620. * - adjustPitch: used to make an adjustment to the pitch of the bone
  71621. * - adjustRoll: used to make an adjustment to the roll of the bone
  71622. **/
  71623. function BoneLookController(mesh, bone, target, options) {
  71624. /**
  71625. * The up axis of the coordinate system that is used when the bone is rotated.
  71626. */
  71627. this.upAxis = BABYLON.Vector3.Up();
  71628. /**
  71629. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71630. */
  71631. this.upAxisSpace = BABYLON.Space.LOCAL;
  71632. /**
  71633. * Used to make an adjustment to the yaw of the bone.
  71634. */
  71635. this.adjustYaw = 0;
  71636. /**
  71637. * Used to make an adjustment to the pitch of the bone.
  71638. */
  71639. this.adjustPitch = 0;
  71640. /**
  71641. * Used to make an adjustment to the roll of the bone.
  71642. */
  71643. this.adjustRoll = 0;
  71644. /**
  71645. * 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).
  71646. */
  71647. this.slerpAmount = 1;
  71648. this._boneQuat = BABYLON.Quaternion.Identity();
  71649. this._slerping = false;
  71650. this._firstFrameSkipped = false;
  71651. this._fowardAxis = BABYLON.Vector3.Forward();
  71652. this.mesh = mesh;
  71653. this.bone = bone;
  71654. this.target = target;
  71655. if (options) {
  71656. if (options.adjustYaw) {
  71657. this.adjustYaw = options.adjustYaw;
  71658. }
  71659. if (options.adjustPitch) {
  71660. this.adjustPitch = options.adjustPitch;
  71661. }
  71662. if (options.adjustRoll) {
  71663. this.adjustRoll = options.adjustRoll;
  71664. }
  71665. if (options.maxYaw != null) {
  71666. this.maxYaw = options.maxYaw;
  71667. }
  71668. else {
  71669. this.maxYaw = Math.PI;
  71670. }
  71671. if (options.minYaw != null) {
  71672. this.minYaw = options.minYaw;
  71673. }
  71674. else {
  71675. this.minYaw = -Math.PI;
  71676. }
  71677. if (options.maxPitch != null) {
  71678. this.maxPitch = options.maxPitch;
  71679. }
  71680. else {
  71681. this.maxPitch = Math.PI;
  71682. }
  71683. if (options.minPitch != null) {
  71684. this.minPitch = options.minPitch;
  71685. }
  71686. else {
  71687. this.minPitch = -Math.PI;
  71688. }
  71689. if (options.slerpAmount != null) {
  71690. this.slerpAmount = options.slerpAmount;
  71691. }
  71692. if (options.upAxis != null) {
  71693. this.upAxis = options.upAxis;
  71694. }
  71695. if (options.upAxisSpace != null) {
  71696. this.upAxisSpace = options.upAxisSpace;
  71697. }
  71698. if (options.yawAxis != null || options.pitchAxis != null) {
  71699. var newYawAxis = BABYLON.Axis.Y;
  71700. var newPitchAxis = BABYLON.Axis.X;
  71701. if (options.yawAxis != null) {
  71702. newYawAxis = options.yawAxis.clone();
  71703. newYawAxis.normalize();
  71704. }
  71705. if (options.pitchAxis != null) {
  71706. newPitchAxis = options.pitchAxis.clone();
  71707. newPitchAxis.normalize();
  71708. }
  71709. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  71710. this._transformYawPitch = BABYLON.Matrix.Identity();
  71711. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  71712. this._transformYawPitchInv = this._transformYawPitch.clone();
  71713. this._transformYawPitch.invert();
  71714. }
  71715. }
  71716. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  71717. this.upAxisSpace = BABYLON.Space.LOCAL;
  71718. }
  71719. }
  71720. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  71721. /**
  71722. * Get/set the minimum yaw angle that the bone can look to.
  71723. */
  71724. get: function () {
  71725. return this._minYaw;
  71726. },
  71727. set: function (value) {
  71728. this._minYaw = value;
  71729. this._minYawSin = Math.sin(value);
  71730. this._minYawCos = Math.cos(value);
  71731. if (this._maxYaw != null) {
  71732. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71733. this._yawRange = this._maxYaw - this._minYaw;
  71734. }
  71735. },
  71736. enumerable: true,
  71737. configurable: true
  71738. });
  71739. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  71740. /**
  71741. * Get/set the maximum yaw angle that the bone can look to.
  71742. */
  71743. get: function () {
  71744. return this._maxYaw;
  71745. },
  71746. set: function (value) {
  71747. this._maxYaw = value;
  71748. this._maxYawSin = Math.sin(value);
  71749. this._maxYawCos = Math.cos(value);
  71750. if (this._minYaw != null) {
  71751. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71752. this._yawRange = this._maxYaw - this._minYaw;
  71753. }
  71754. },
  71755. enumerable: true,
  71756. configurable: true
  71757. });
  71758. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  71759. /**
  71760. * Get/set the minimum pitch angle that the bone can look to.
  71761. */
  71762. get: function () {
  71763. return this._minPitch;
  71764. },
  71765. set: function (value) {
  71766. this._minPitch = value;
  71767. this._minPitchTan = Math.tan(value);
  71768. },
  71769. enumerable: true,
  71770. configurable: true
  71771. });
  71772. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  71773. /**
  71774. * Get/set the maximum pitch angle that the bone can look to.
  71775. */
  71776. get: function () {
  71777. return this._maxPitch;
  71778. },
  71779. set: function (value) {
  71780. this._maxPitch = value;
  71781. this._maxPitchTan = Math.tan(value);
  71782. },
  71783. enumerable: true,
  71784. configurable: true
  71785. });
  71786. /**
  71787. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  71788. */
  71789. BoneLookController.prototype.update = function () {
  71790. //skip the first frame when slerping so that the mesh rotation is correct
  71791. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  71792. this._firstFrameSkipped = true;
  71793. return;
  71794. }
  71795. var bone = this.bone;
  71796. var bonePos = BoneLookController._tmpVecs[0];
  71797. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  71798. var target = this.target;
  71799. var _tmpMat1 = BoneLookController._tmpMats[0];
  71800. var _tmpMat2 = BoneLookController._tmpMats[1];
  71801. var mesh = this.mesh;
  71802. var parentBone = bone.getParent();
  71803. var upAxis = BoneLookController._tmpVecs[1];
  71804. upAxis.copyFrom(this.upAxis);
  71805. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  71806. if (this._transformYawPitch) {
  71807. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  71808. }
  71809. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  71810. }
  71811. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  71812. mesh.getDirectionToRef(upAxis, upAxis);
  71813. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  71814. upAxis.normalize();
  71815. }
  71816. }
  71817. var checkYaw = false;
  71818. var checkPitch = false;
  71819. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  71820. checkYaw = true;
  71821. }
  71822. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  71823. checkPitch = true;
  71824. }
  71825. if (checkYaw || checkPitch) {
  71826. var spaceMat = BoneLookController._tmpMats[2];
  71827. var spaceMatInv = BoneLookController._tmpMats[3];
  71828. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  71829. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  71830. }
  71831. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  71832. spaceMat.copyFrom(mesh.getWorldMatrix());
  71833. }
  71834. else {
  71835. var forwardAxis = BoneLookController._tmpVecs[2];
  71836. forwardAxis.copyFrom(this._fowardAxis);
  71837. if (this._transformYawPitch) {
  71838. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  71839. }
  71840. if (parentBone) {
  71841. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  71842. }
  71843. else {
  71844. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  71845. }
  71846. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  71847. rightAxis.normalize();
  71848. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  71849. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  71850. }
  71851. spaceMat.invertToRef(spaceMatInv);
  71852. var xzlen = null;
  71853. if (checkPitch) {
  71854. var localTarget = BoneLookController._tmpVecs[3];
  71855. target.subtractToRef(bonePos, localTarget);
  71856. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71857. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71858. var pitch = Math.atan2(localTarget.y, xzlen);
  71859. var newPitch = pitch;
  71860. if (pitch > this._maxPitch) {
  71861. localTarget.y = this._maxPitchTan * xzlen;
  71862. newPitch = this._maxPitch;
  71863. }
  71864. else if (pitch < this._minPitch) {
  71865. localTarget.y = this._minPitchTan * xzlen;
  71866. newPitch = this._minPitch;
  71867. }
  71868. if (pitch != newPitch) {
  71869. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71870. localTarget.addInPlace(bonePos);
  71871. target = localTarget;
  71872. }
  71873. }
  71874. if (checkYaw) {
  71875. var localTarget = BoneLookController._tmpVecs[4];
  71876. target.subtractToRef(bonePos, localTarget);
  71877. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71878. var yaw = Math.atan2(localTarget.x, localTarget.z);
  71879. var newYaw = yaw;
  71880. if (yaw > this._maxYaw || yaw < this._minYaw) {
  71881. if (xzlen == null) {
  71882. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71883. }
  71884. if (this._yawRange > Math.PI) {
  71885. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  71886. localTarget.z = this._maxYawCos * xzlen;
  71887. localTarget.x = this._maxYawSin * xzlen;
  71888. newYaw = this._maxYaw;
  71889. }
  71890. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  71891. localTarget.z = this._minYawCos * xzlen;
  71892. localTarget.x = this._minYawSin * xzlen;
  71893. newYaw = this._minYaw;
  71894. }
  71895. }
  71896. else {
  71897. if (yaw > this._maxYaw) {
  71898. localTarget.z = this._maxYawCos * xzlen;
  71899. localTarget.x = this._maxYawSin * xzlen;
  71900. newYaw = this._maxYaw;
  71901. }
  71902. else if (yaw < this._minYaw) {
  71903. localTarget.z = this._minYawCos * xzlen;
  71904. localTarget.x = this._minYawSin * xzlen;
  71905. newYaw = this._minYaw;
  71906. }
  71907. }
  71908. }
  71909. if (this._slerping && this._yawRange > Math.PI) {
  71910. //are we going to be crossing into the min/max region?
  71911. var boneFwd = BoneLookController._tmpVecs[8];
  71912. boneFwd.copyFrom(BABYLON.Axis.Z);
  71913. if (this._transformYawPitch) {
  71914. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  71915. }
  71916. var boneRotMat = BoneLookController._tmpMats[4];
  71917. this._boneQuat.toRotationMatrix(boneRotMat);
  71918. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  71919. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  71920. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  71921. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  71922. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  71923. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  71924. if (angBtwTar > angBtwMidYaw) {
  71925. if (xzlen == null) {
  71926. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71927. }
  71928. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  71929. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  71930. if (angBtwMin < angBtwMax) {
  71931. newYaw = boneYaw + Math.PI * .75;
  71932. localTarget.z = Math.cos(newYaw) * xzlen;
  71933. localTarget.x = Math.sin(newYaw) * xzlen;
  71934. }
  71935. else {
  71936. newYaw = boneYaw - Math.PI * .75;
  71937. localTarget.z = Math.cos(newYaw) * xzlen;
  71938. localTarget.x = Math.sin(newYaw) * xzlen;
  71939. }
  71940. }
  71941. }
  71942. if (yaw != newYaw) {
  71943. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71944. localTarget.addInPlace(bonePos);
  71945. target = localTarget;
  71946. }
  71947. }
  71948. }
  71949. var zaxis = BoneLookController._tmpVecs[5];
  71950. var xaxis = BoneLookController._tmpVecs[6];
  71951. var yaxis = BoneLookController._tmpVecs[7];
  71952. var _tmpQuat = BoneLookController._tmpQuat;
  71953. target.subtractToRef(bonePos, zaxis);
  71954. zaxis.normalize();
  71955. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  71956. xaxis.normalize();
  71957. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  71958. yaxis.normalize();
  71959. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  71960. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  71961. return;
  71962. }
  71963. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  71964. return;
  71965. }
  71966. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  71967. return;
  71968. }
  71969. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  71970. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  71971. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  71972. }
  71973. if (this.slerpAmount < 1) {
  71974. if (!this._slerping) {
  71975. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  71976. }
  71977. if (this._transformYawPitch) {
  71978. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71979. }
  71980. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  71981. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  71982. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  71983. this._slerping = true;
  71984. }
  71985. else {
  71986. if (this._transformYawPitch) {
  71987. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71988. }
  71989. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  71990. this._slerping = false;
  71991. }
  71992. };
  71993. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  71994. var angDiff = ang2 - ang1;
  71995. angDiff %= Math.PI * 2;
  71996. if (angDiff > Math.PI) {
  71997. angDiff -= Math.PI * 2;
  71998. }
  71999. else if (angDiff < -Math.PI) {
  72000. angDiff += Math.PI * 2;
  72001. }
  72002. return angDiff;
  72003. };
  72004. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  72005. ang1 %= (2 * Math.PI);
  72006. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72007. ang2 %= (2 * Math.PI);
  72008. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72009. var ab = 0;
  72010. if (ang1 < ang2) {
  72011. ab = ang2 - ang1;
  72012. }
  72013. else {
  72014. ab = ang1 - ang2;
  72015. }
  72016. if (ab > Math.PI) {
  72017. ab = Math.PI * 2 - ab;
  72018. }
  72019. return ab;
  72020. };
  72021. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  72022. ang %= (2 * Math.PI);
  72023. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  72024. ang1 %= (2 * Math.PI);
  72025. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72026. ang2 %= (2 * Math.PI);
  72027. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72028. if (ang1 < ang2) {
  72029. if (ang > ang1 && ang < ang2) {
  72030. return true;
  72031. }
  72032. }
  72033. else {
  72034. if (ang > ang2 && ang < ang1) {
  72035. return true;
  72036. }
  72037. }
  72038. return false;
  72039. };
  72040. 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()];
  72041. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  72042. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72043. return BoneLookController;
  72044. }());
  72045. BABYLON.BoneLookController = BoneLookController;
  72046. })(BABYLON || (BABYLON = {}));
  72047. //# sourceMappingURL=babylon.boneLookController.js.map
  72048. var BABYLON;
  72049. (function (BABYLON) {
  72050. var Skeleton = /** @class */ (function () {
  72051. function Skeleton(name, id, scene) {
  72052. this.name = name;
  72053. this.id = id;
  72054. this.bones = new Array();
  72055. this.needInitialSkinMatrix = false;
  72056. this._isDirty = true;
  72057. this._meshesWithPoseMatrix = new Array();
  72058. this._identity = BABYLON.Matrix.Identity();
  72059. this._ranges = {};
  72060. this._lastAbsoluteTransformsUpdateId = -1;
  72061. /**
  72062. * Specifies if the skeleton should be serialized.
  72063. */
  72064. this.doNotSerialize = false;
  72065. // Events
  72066. /**
  72067. * An event triggered before computing the skeleton's matrices
  72068. * @type {BABYLON.Observable}
  72069. */
  72070. this.onBeforeComputeObservable = new BABYLON.Observable();
  72071. this.bones = [];
  72072. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72073. scene.skeletons.push(this);
  72074. //make sure it will recalculate the matrix next time prepare is called.
  72075. this._isDirty = true;
  72076. }
  72077. // Members
  72078. Skeleton.prototype.getTransformMatrices = function (mesh) {
  72079. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  72080. return mesh._bonesTransformMatrices;
  72081. }
  72082. if (!this._transformMatrices) {
  72083. this.prepare();
  72084. }
  72085. return this._transformMatrices;
  72086. };
  72087. Skeleton.prototype.getScene = function () {
  72088. return this._scene;
  72089. };
  72090. // Methods
  72091. /**
  72092. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  72093. */
  72094. Skeleton.prototype.toString = function (fullDetails) {
  72095. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  72096. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  72097. if (fullDetails) {
  72098. ret += ", Ranges: {";
  72099. var first = true;
  72100. for (var name_1 in this._ranges) {
  72101. if (first) {
  72102. ret += ", ";
  72103. first = false;
  72104. }
  72105. ret += name_1;
  72106. }
  72107. ret += "}";
  72108. }
  72109. return ret;
  72110. };
  72111. /**
  72112. * Get bone's index searching by name
  72113. * @param {string} name is bone's name to search for
  72114. * @return {number} Indice of the bone. Returns -1 if not found
  72115. */
  72116. Skeleton.prototype.getBoneIndexByName = function (name) {
  72117. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  72118. if (this.bones[boneIndex].name === name) {
  72119. return boneIndex;
  72120. }
  72121. }
  72122. return -1;
  72123. };
  72124. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  72125. // check name not already in use
  72126. if (!this._ranges[name]) {
  72127. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  72128. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72129. if (this.bones[i].animations[0]) {
  72130. this.bones[i].animations[0].createRange(name, from, to);
  72131. }
  72132. }
  72133. }
  72134. };
  72135. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  72136. if (deleteFrames === void 0) { deleteFrames = true; }
  72137. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72138. if (this.bones[i].animations[0]) {
  72139. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  72140. }
  72141. }
  72142. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  72143. };
  72144. Skeleton.prototype.getAnimationRange = function (name) {
  72145. return this._ranges[name];
  72146. };
  72147. /**
  72148. * Returns as an Array, all AnimationRanges defined on this skeleton
  72149. */
  72150. Skeleton.prototype.getAnimationRanges = function () {
  72151. var animationRanges = [];
  72152. var name;
  72153. var i = 0;
  72154. for (name in this._ranges) {
  72155. animationRanges[i] = this._ranges[name];
  72156. i++;
  72157. }
  72158. return animationRanges;
  72159. };
  72160. /**
  72161. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  72162. */
  72163. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  72164. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72165. if (this._ranges[name] || !source.getAnimationRange(name)) {
  72166. return false;
  72167. }
  72168. var ret = true;
  72169. var frameOffset = this._getHighestAnimationFrame() + 1;
  72170. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  72171. var boneDict = {};
  72172. var sourceBones = source.bones;
  72173. var nBones;
  72174. var i;
  72175. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  72176. boneDict[sourceBones[i].name] = sourceBones[i];
  72177. }
  72178. if (this.bones.length !== sourceBones.length) {
  72179. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  72180. ret = false;
  72181. }
  72182. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  72183. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  72184. var boneName = this.bones[i].name;
  72185. var sourceBone = boneDict[boneName];
  72186. if (sourceBone) {
  72187. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  72188. }
  72189. else {
  72190. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  72191. ret = false;
  72192. }
  72193. }
  72194. // do not call createAnimationRange(), since it also is done to bones, which was already done
  72195. var range = source.getAnimationRange(name);
  72196. if (range) {
  72197. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  72198. }
  72199. return ret;
  72200. };
  72201. Skeleton.prototype.returnToRest = function () {
  72202. for (var index = 0; index < this.bones.length; index++) {
  72203. this.bones[index].returnToRest();
  72204. }
  72205. };
  72206. Skeleton.prototype._getHighestAnimationFrame = function () {
  72207. var ret = 0;
  72208. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72209. if (this.bones[i].animations[0]) {
  72210. var highest = this.bones[i].animations[0].getHighestFrame();
  72211. if (ret < highest) {
  72212. ret = highest;
  72213. }
  72214. }
  72215. }
  72216. return ret;
  72217. };
  72218. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  72219. var range = this.getAnimationRange(name);
  72220. if (!range) {
  72221. return null;
  72222. }
  72223. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  72224. };
  72225. Skeleton.prototype._markAsDirty = function () {
  72226. this._isDirty = true;
  72227. };
  72228. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  72229. this._meshesWithPoseMatrix.push(mesh);
  72230. };
  72231. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  72232. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  72233. if (index > -1) {
  72234. this._meshesWithPoseMatrix.splice(index, 1);
  72235. }
  72236. };
  72237. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  72238. this.onBeforeComputeObservable.notifyObservers(this);
  72239. for (var index = 0; index < this.bones.length; index++) {
  72240. var bone = this.bones[index];
  72241. var parentBone = bone.getParent();
  72242. if (parentBone) {
  72243. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  72244. }
  72245. else {
  72246. if (initialSkinMatrix) {
  72247. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  72248. }
  72249. else {
  72250. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  72251. }
  72252. }
  72253. if (bone._index !== -1) {
  72254. var mappedIndex = bone._index === null ? index : bone._index;
  72255. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  72256. }
  72257. }
  72258. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  72259. };
  72260. Skeleton.prototype.prepare = function () {
  72261. if (!this._isDirty) {
  72262. return;
  72263. }
  72264. if (this.needInitialSkinMatrix) {
  72265. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  72266. var mesh = this._meshesWithPoseMatrix[index];
  72267. var poseMatrix = mesh.getPoseMatrix();
  72268. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  72269. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72270. }
  72271. if (this._synchronizedWithMesh !== mesh) {
  72272. this._synchronizedWithMesh = mesh;
  72273. // Prepare bones
  72274. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  72275. var bone = this.bones[boneIndex];
  72276. if (!bone.getParent()) {
  72277. var matrix = bone.getBaseMatrix();
  72278. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  72279. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  72280. }
  72281. }
  72282. }
  72283. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  72284. }
  72285. }
  72286. else {
  72287. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  72288. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  72289. }
  72290. this._computeTransformMatrices(this._transformMatrices, null);
  72291. }
  72292. this._isDirty = false;
  72293. this._scene._activeBones.addCount(this.bones.length, false);
  72294. };
  72295. Skeleton.prototype.getAnimatables = function () {
  72296. if (!this._animatables || this._animatables.length !== this.bones.length) {
  72297. this._animatables = [];
  72298. for (var index = 0; index < this.bones.length; index++) {
  72299. this._animatables.push(this.bones[index]);
  72300. }
  72301. }
  72302. return this._animatables;
  72303. };
  72304. Skeleton.prototype.clone = function (name, id) {
  72305. var result = new Skeleton(name, id || name, this._scene);
  72306. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72307. for (var index = 0; index < this.bones.length; index++) {
  72308. var source = this.bones[index];
  72309. var parentBone = null;
  72310. var parent_1 = source.getParent();
  72311. if (parent_1) {
  72312. var parentIndex = this.bones.indexOf(parent_1);
  72313. parentBone = result.bones[parentIndex];
  72314. }
  72315. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  72316. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  72317. }
  72318. if (this._ranges) {
  72319. result._ranges = {};
  72320. for (var rangeName in this._ranges) {
  72321. var range = this._ranges[rangeName];
  72322. if (range) {
  72323. result._ranges[rangeName] = range.clone();
  72324. }
  72325. }
  72326. }
  72327. this._isDirty = true;
  72328. return result;
  72329. };
  72330. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  72331. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  72332. this.bones.forEach(function (bone) {
  72333. bone.animations.forEach(function (animation) {
  72334. animation.enableBlending = true;
  72335. animation.blendingSpeed = blendingSpeed;
  72336. });
  72337. });
  72338. };
  72339. Skeleton.prototype.dispose = function () {
  72340. this._meshesWithPoseMatrix = [];
  72341. // Animations
  72342. this.getScene().stopAnimation(this);
  72343. // Remove from scene
  72344. this.getScene().removeSkeleton(this);
  72345. };
  72346. Skeleton.prototype.serialize = function () {
  72347. var serializationObject = {};
  72348. serializationObject.name = this.name;
  72349. serializationObject.id = this.id;
  72350. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  72351. serializationObject.bones = [];
  72352. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  72353. for (var index = 0; index < this.bones.length; index++) {
  72354. var bone = this.bones[index];
  72355. var parent_2 = bone.getParent();
  72356. var serializedBone = {
  72357. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  72358. name: bone.name,
  72359. matrix: bone.getBaseMatrix().toArray(),
  72360. rest: bone.getRestPose().toArray()
  72361. };
  72362. serializationObject.bones.push(serializedBone);
  72363. if (bone.length) {
  72364. serializedBone.length = bone.length;
  72365. }
  72366. if (bone.animations && bone.animations.length > 0) {
  72367. serializedBone.animation = bone.animations[0].serialize();
  72368. }
  72369. serializationObject.ranges = [];
  72370. for (var name in this._ranges) {
  72371. var source = this._ranges[name];
  72372. if (!source) {
  72373. continue;
  72374. }
  72375. var range = {};
  72376. range.name = name;
  72377. range.from = source.from;
  72378. range.to = source.to;
  72379. serializationObject.ranges.push(range);
  72380. }
  72381. }
  72382. return serializationObject;
  72383. };
  72384. Skeleton.Parse = function (parsedSkeleton, scene) {
  72385. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  72386. if (parsedSkeleton.dimensionsAtRest) {
  72387. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  72388. }
  72389. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  72390. var index;
  72391. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  72392. var parsedBone = parsedSkeleton.bones[index];
  72393. var parentBone = null;
  72394. if (parsedBone.parentBoneIndex > -1) {
  72395. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  72396. }
  72397. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  72398. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  72399. if (parsedBone.length) {
  72400. bone.length = parsedBone.length;
  72401. }
  72402. if (parsedBone.animation) {
  72403. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  72404. }
  72405. }
  72406. // placed after bones, so createAnimationRange can cascade down
  72407. if (parsedSkeleton.ranges) {
  72408. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  72409. var data = parsedSkeleton.ranges[index];
  72410. skeleton.createAnimationRange(data.name, data.from, data.to);
  72411. }
  72412. }
  72413. return skeleton;
  72414. };
  72415. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  72416. if (forceUpdate === void 0) { forceUpdate = false; }
  72417. var renderId = this._scene.getRenderId();
  72418. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  72419. this.bones[0].computeAbsoluteTransforms();
  72420. this._lastAbsoluteTransformsUpdateId = renderId;
  72421. }
  72422. };
  72423. Skeleton.prototype.getPoseMatrix = function () {
  72424. var poseMatrix = null;
  72425. if (this._meshesWithPoseMatrix.length > 0) {
  72426. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  72427. }
  72428. return poseMatrix;
  72429. };
  72430. Skeleton.prototype.sortBones = function () {
  72431. var bones = new Array();
  72432. var visited = new Array(this.bones.length);
  72433. for (var index = 0; index < this.bones.length; index++) {
  72434. this._sortBones(index, bones, visited);
  72435. }
  72436. this.bones = bones;
  72437. };
  72438. Skeleton.prototype._sortBones = function (index, bones, visited) {
  72439. if (visited[index]) {
  72440. return;
  72441. }
  72442. visited[index] = true;
  72443. var bone = this.bones[index];
  72444. if (bone._index === undefined) {
  72445. bone._index = index;
  72446. }
  72447. var parentBone = bone.getParent();
  72448. if (parentBone) {
  72449. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  72450. }
  72451. bones.push(bone);
  72452. };
  72453. return Skeleton;
  72454. }());
  72455. BABYLON.Skeleton = Skeleton;
  72456. })(BABYLON || (BABYLON = {}));
  72457. //# sourceMappingURL=babylon.skeleton.js.map
  72458. var BABYLON;
  72459. (function (BABYLON) {
  72460. var SphericalPolynomial = /** @class */ (function () {
  72461. function SphericalPolynomial() {
  72462. this.x = BABYLON.Vector3.Zero();
  72463. this.y = BABYLON.Vector3.Zero();
  72464. this.z = BABYLON.Vector3.Zero();
  72465. this.xx = BABYLON.Vector3.Zero();
  72466. this.yy = BABYLON.Vector3.Zero();
  72467. this.zz = BABYLON.Vector3.Zero();
  72468. this.xy = BABYLON.Vector3.Zero();
  72469. this.yz = BABYLON.Vector3.Zero();
  72470. this.zx = BABYLON.Vector3.Zero();
  72471. }
  72472. SphericalPolynomial.prototype.addAmbient = function (color) {
  72473. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72474. this.xx = this.xx.add(colorVector);
  72475. this.yy = this.yy.add(colorVector);
  72476. this.zz = this.zz.add(colorVector);
  72477. };
  72478. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  72479. var result = new SphericalPolynomial();
  72480. result.x = harmonics.L11.scale(1.02333);
  72481. result.y = harmonics.L1_1.scale(1.02333);
  72482. result.z = harmonics.L10.scale(1.02333);
  72483. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  72484. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  72485. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  72486. result.yz = harmonics.L2_1.scale(0.858086);
  72487. result.zx = harmonics.L21.scale(0.858086);
  72488. result.xy = harmonics.L2_2.scale(0.858086);
  72489. result.scale(1.0 / Math.PI);
  72490. return result;
  72491. };
  72492. SphericalPolynomial.prototype.scale = function (scale) {
  72493. this.x = this.x.scale(scale);
  72494. this.y = this.y.scale(scale);
  72495. this.z = this.z.scale(scale);
  72496. this.xx = this.xx.scale(scale);
  72497. this.yy = this.yy.scale(scale);
  72498. this.zz = this.zz.scale(scale);
  72499. this.yz = this.yz.scale(scale);
  72500. this.zx = this.zx.scale(scale);
  72501. this.xy = this.xy.scale(scale);
  72502. };
  72503. return SphericalPolynomial;
  72504. }());
  72505. BABYLON.SphericalPolynomial = SphericalPolynomial;
  72506. var SphericalHarmonics = /** @class */ (function () {
  72507. function SphericalHarmonics() {
  72508. this.L00 = BABYLON.Vector3.Zero();
  72509. this.L1_1 = BABYLON.Vector3.Zero();
  72510. this.L10 = BABYLON.Vector3.Zero();
  72511. this.L11 = BABYLON.Vector3.Zero();
  72512. this.L2_2 = BABYLON.Vector3.Zero();
  72513. this.L2_1 = BABYLON.Vector3.Zero();
  72514. this.L20 = BABYLON.Vector3.Zero();
  72515. this.L21 = BABYLON.Vector3.Zero();
  72516. this.L22 = BABYLON.Vector3.Zero();
  72517. }
  72518. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  72519. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  72520. var c = colorVector.scale(deltaSolidAngle);
  72521. this.L00 = this.L00.add(c.scale(0.282095));
  72522. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  72523. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  72524. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  72525. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  72526. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  72527. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  72528. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  72529. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  72530. };
  72531. SphericalHarmonics.prototype.scale = function (scale) {
  72532. this.L00 = this.L00.scale(scale);
  72533. this.L1_1 = this.L1_1.scale(scale);
  72534. this.L10 = this.L10.scale(scale);
  72535. this.L11 = this.L11.scale(scale);
  72536. this.L2_2 = this.L2_2.scale(scale);
  72537. this.L2_1 = this.L2_1.scale(scale);
  72538. this.L20 = this.L20.scale(scale);
  72539. this.L21 = this.L21.scale(scale);
  72540. this.L22 = this.L22.scale(scale);
  72541. };
  72542. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  72543. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  72544. //
  72545. // E_lm = A_l * L_lm
  72546. //
  72547. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  72548. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  72549. // the scaling factors are given in equation 9.
  72550. // Constant (Band 0)
  72551. this.L00 = this.L00.scale(3.141593);
  72552. // Linear (Band 1)
  72553. this.L1_1 = this.L1_1.scale(2.094395);
  72554. this.L10 = this.L10.scale(2.094395);
  72555. this.L11 = this.L11.scale(2.094395);
  72556. // Quadratic (Band 2)
  72557. this.L2_2 = this.L2_2.scale(0.785398);
  72558. this.L2_1 = this.L2_1.scale(0.785398);
  72559. this.L20 = this.L20.scale(0.785398);
  72560. this.L21 = this.L21.scale(0.785398);
  72561. this.L22 = this.L22.scale(0.785398);
  72562. };
  72563. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  72564. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  72565. // L = (1/pi) * E * rho
  72566. //
  72567. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  72568. this.scale(1.0 / Math.PI);
  72569. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  72570. // (The pixel shader must apply albedo after texture fetches, etc).
  72571. };
  72572. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  72573. var result = new SphericalHarmonics();
  72574. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  72575. result.L1_1 = polynomial.y.scale(0.977204);
  72576. result.L10 = polynomial.z.scale(0.977204);
  72577. result.L11 = polynomial.x.scale(0.977204);
  72578. result.L2_2 = polynomial.xy.scale(1.16538);
  72579. result.L2_1 = polynomial.yz.scale(1.16538);
  72580. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  72581. result.L21 = polynomial.zx.scale(1.16538);
  72582. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  72583. result.scale(Math.PI);
  72584. return result;
  72585. };
  72586. return SphericalHarmonics;
  72587. }());
  72588. BABYLON.SphericalHarmonics = SphericalHarmonics;
  72589. })(BABYLON || (BABYLON = {}));
  72590. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  72591. var BABYLON;
  72592. (function (BABYLON) {
  72593. var FileFaceOrientation = /** @class */ (function () {
  72594. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  72595. this.name = name;
  72596. this.worldAxisForNormal = worldAxisForNormal;
  72597. this.worldAxisForFileX = worldAxisForFileX;
  72598. this.worldAxisForFileY = worldAxisForFileY;
  72599. }
  72600. return FileFaceOrientation;
  72601. }());
  72602. ;
  72603. /**
  72604. * Helper class dealing with the extraction of spherical polynomial dataArray
  72605. * from a cube map.
  72606. */
  72607. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  72608. function CubeMapToSphericalPolynomialTools() {
  72609. }
  72610. /**
  72611. * Converts a texture to the according Spherical Polynomial data.
  72612. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72613. *
  72614. * @param texture The texture to extract the information from.
  72615. * @return The Spherical Polynomial data.
  72616. */
  72617. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  72618. if (!texture.isCube) {
  72619. // Only supports cube Textures currently.
  72620. return null;
  72621. }
  72622. var size = texture.getSize().width;
  72623. var right = texture.readPixels(0);
  72624. var left = texture.readPixels(1);
  72625. var up;
  72626. var down;
  72627. if (texture.isRenderTarget) {
  72628. up = texture.readPixels(3);
  72629. down = texture.readPixels(2);
  72630. }
  72631. else {
  72632. up = texture.readPixels(2);
  72633. down = texture.readPixels(3);
  72634. }
  72635. var front = texture.readPixels(4);
  72636. var back = texture.readPixels(5);
  72637. var gammaSpace = texture.gammaSpace;
  72638. // Always read as RGBA.
  72639. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  72640. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72641. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72642. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72643. }
  72644. var cubeInfo = {
  72645. size: size,
  72646. right: right,
  72647. left: left,
  72648. up: up,
  72649. down: down,
  72650. front: front,
  72651. back: back,
  72652. format: format,
  72653. type: type,
  72654. gammaSpace: gammaSpace,
  72655. };
  72656. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  72657. };
  72658. /**
  72659. * Converts a cubemap to the according Spherical Polynomial data.
  72660. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72661. *
  72662. * @param cubeInfo The Cube map to extract the information from.
  72663. * @return The Spherical Polynomial data.
  72664. */
  72665. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  72666. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  72667. var totalSolidAngle = 0.0;
  72668. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  72669. var du = 2.0 / cubeInfo.size;
  72670. var dv = du;
  72671. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  72672. var minUV = du * 0.5 - 1.0;
  72673. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72674. var fileFace = this.FileFaces[faceIndex];
  72675. var dataArray = cubeInfo[fileFace.name];
  72676. var v = minUV;
  72677. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  72678. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  72679. // Because SP is still linear, so summation is fine in that basis.
  72680. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  72681. for (var y = 0; y < cubeInfo.size; y++) {
  72682. var u = minUV;
  72683. for (var x = 0; x < cubeInfo.size; x++) {
  72684. // World direction (not normalised)
  72685. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  72686. worldDirection.normalize();
  72687. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  72688. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  72689. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  72690. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  72691. // Handle Integer types.
  72692. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72693. r /= 255;
  72694. g /= 255;
  72695. b /= 255;
  72696. }
  72697. // Handle Gamma space textures.
  72698. if (cubeInfo.gammaSpace) {
  72699. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  72700. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  72701. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  72702. }
  72703. var color = new BABYLON.Color3(r, g, b);
  72704. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  72705. totalSolidAngle += deltaSolidAngle;
  72706. u += du;
  72707. }
  72708. v += dv;
  72709. }
  72710. }
  72711. // Solid angle for entire sphere is 4*pi
  72712. var sphereSolidAngle = 4.0 * Math.PI;
  72713. // Adjust the solid angle to allow for how many faces we processed.
  72714. var facesProcessed = 6.0;
  72715. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  72716. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  72717. // This is needed because the numerical integration over the cube uses a
  72718. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  72719. // and also to compensate for accumulative error due to float precision in the summation.
  72720. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  72721. sphericalHarmonics.scale(correctionFactor);
  72722. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  72723. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  72724. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  72725. };
  72726. CubeMapToSphericalPolynomialTools.FileFaces = [
  72727. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  72728. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  72729. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  72730. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  72731. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  72732. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  72733. ];
  72734. return CubeMapToSphericalPolynomialTools;
  72735. }());
  72736. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  72737. })(BABYLON || (BABYLON = {}));
  72738. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  72739. var BABYLON;
  72740. (function (BABYLON) {
  72741. /**
  72742. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  72743. */
  72744. var PanoramaToCubeMapTools = /** @class */ (function () {
  72745. function PanoramaToCubeMapTools() {
  72746. }
  72747. /**
  72748. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  72749. *
  72750. * @param float32Array The source data.
  72751. * @param inputWidth The width of the input panorama.
  72752. * @param inputhHeight The height of the input panorama.
  72753. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  72754. * @return The cubemap data
  72755. */
  72756. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  72757. if (!float32Array) {
  72758. throw "ConvertPanoramaToCubemap: input cannot be null";
  72759. }
  72760. if (float32Array.length != inputWidth * inputHeight * 3) {
  72761. throw "ConvertPanoramaToCubemap: input size is wrong";
  72762. }
  72763. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  72764. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  72765. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  72766. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  72767. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  72768. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  72769. return {
  72770. front: textureFront,
  72771. back: textureBack,
  72772. left: textureLeft,
  72773. right: textureRight,
  72774. up: textureUp,
  72775. down: textureDown,
  72776. size: size,
  72777. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  72778. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  72779. gammaSpace: false,
  72780. };
  72781. };
  72782. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  72783. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  72784. var textureArray = new Float32Array(buffer);
  72785. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  72786. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  72787. var dy = 1 / texSize;
  72788. var fy = 0;
  72789. for (var y = 0; y < texSize; y++) {
  72790. var xv1 = faceData[0];
  72791. var xv2 = faceData[2];
  72792. for (var x = 0; x < texSize; x++) {
  72793. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  72794. v.normalize();
  72795. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  72796. // 3 channels per pixels
  72797. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  72798. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  72799. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  72800. xv1 = xv1.add(rotDX1);
  72801. xv2 = xv2.add(rotDX2);
  72802. }
  72803. fy += dy;
  72804. }
  72805. return textureArray;
  72806. };
  72807. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  72808. var theta = Math.atan2(vDir.z, vDir.x);
  72809. var phi = Math.acos(vDir.y);
  72810. while (theta < -Math.PI)
  72811. theta += 2 * Math.PI;
  72812. while (theta > Math.PI)
  72813. theta -= 2 * Math.PI;
  72814. var dx = theta / Math.PI;
  72815. var dy = phi / Math.PI;
  72816. // recenter.
  72817. dx = dx * 0.5 + 0.5;
  72818. var px = Math.round(dx * inputWidth);
  72819. if (px < 0)
  72820. px = 0;
  72821. else if (px >= inputWidth)
  72822. px = inputWidth - 1;
  72823. var py = Math.round(dy * inputHeight);
  72824. if (py < 0)
  72825. py = 0;
  72826. else if (py >= inputHeight)
  72827. py = inputHeight - 1;
  72828. var inputY = (inputHeight - py - 1);
  72829. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  72830. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  72831. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  72832. return {
  72833. r: r,
  72834. g: g,
  72835. b: b
  72836. };
  72837. };
  72838. PanoramaToCubeMapTools.FACE_FRONT = [
  72839. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72840. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72841. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72842. new BABYLON.Vector3(1.0, 1.0, -1.0)
  72843. ];
  72844. PanoramaToCubeMapTools.FACE_BACK = [
  72845. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72846. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72847. new BABYLON.Vector3(1.0, 1.0, 1.0),
  72848. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  72849. ];
  72850. PanoramaToCubeMapTools.FACE_RIGHT = [
  72851. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72852. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72853. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72854. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72855. ];
  72856. PanoramaToCubeMapTools.FACE_LEFT = [
  72857. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72858. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72859. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72860. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  72861. ];
  72862. PanoramaToCubeMapTools.FACE_DOWN = [
  72863. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72864. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72865. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72866. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72867. ];
  72868. PanoramaToCubeMapTools.FACE_UP = [
  72869. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72870. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72871. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72872. new BABYLON.Vector3(1.0, -1.0, -1.0)
  72873. ];
  72874. return PanoramaToCubeMapTools;
  72875. }());
  72876. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  72877. })(BABYLON || (BABYLON = {}));
  72878. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  72879. var BABYLON;
  72880. (function (BABYLON) {
  72881. ;
  72882. /**
  72883. * This groups tools to convert HDR texture to native colors array.
  72884. */
  72885. var HDRTools = /** @class */ (function () {
  72886. function HDRTools() {
  72887. }
  72888. HDRTools.Ldexp = function (mantissa, exponent) {
  72889. if (exponent > 1023) {
  72890. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  72891. }
  72892. if (exponent < -1074) {
  72893. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  72894. }
  72895. return mantissa * Math.pow(2, exponent);
  72896. };
  72897. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  72898. if (exponent > 0) {
  72899. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  72900. float32array[index + 0] = red * exponent;
  72901. float32array[index + 1] = green * exponent;
  72902. float32array[index + 2] = blue * exponent;
  72903. }
  72904. else {
  72905. float32array[index + 0] = 0;
  72906. float32array[index + 1] = 0;
  72907. float32array[index + 2] = 0;
  72908. }
  72909. };
  72910. HDRTools.readStringLine = function (uint8array, startIndex) {
  72911. var line = "";
  72912. var character = "";
  72913. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  72914. character = String.fromCharCode(uint8array[i]);
  72915. if (character == "\n") {
  72916. break;
  72917. }
  72918. line += character;
  72919. }
  72920. return line;
  72921. };
  72922. /**
  72923. * Reads header information from an RGBE texture stored in a native array.
  72924. * More information on this format are available here:
  72925. * https://en.wikipedia.org/wiki/RGBE_image_format
  72926. *
  72927. * @param uint8array The binary file stored in native array.
  72928. * @return The header information.
  72929. */
  72930. HDRTools.RGBE_ReadHeader = function (uint8array) {
  72931. var height = 0;
  72932. var width = 0;
  72933. var line = this.readStringLine(uint8array, 0);
  72934. if (line[0] != '#' || line[1] != '?') {
  72935. throw "Bad HDR Format.";
  72936. }
  72937. var endOfHeader = false;
  72938. var findFormat = false;
  72939. var lineIndex = 0;
  72940. do {
  72941. lineIndex += (line.length + 1);
  72942. line = this.readStringLine(uint8array, lineIndex);
  72943. if (line == "FORMAT=32-bit_rle_rgbe") {
  72944. findFormat = true;
  72945. }
  72946. else if (line.length == 0) {
  72947. endOfHeader = true;
  72948. }
  72949. } while (!endOfHeader);
  72950. if (!findFormat) {
  72951. throw "HDR Bad header format, unsupported FORMAT";
  72952. }
  72953. lineIndex += (line.length + 1);
  72954. line = this.readStringLine(uint8array, lineIndex);
  72955. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  72956. var match = sizeRegexp.exec(line);
  72957. // TODO. Support +Y and -X if needed.
  72958. if (!match || match.length < 3) {
  72959. throw "HDR Bad header format, no size";
  72960. }
  72961. width = parseInt(match[2]);
  72962. height = parseInt(match[1]);
  72963. if (width < 8 || width > 0x7fff) {
  72964. throw "HDR Bad header format, unsupported size";
  72965. }
  72966. lineIndex += (line.length + 1);
  72967. return {
  72968. height: height,
  72969. width: width,
  72970. dataPosition: lineIndex
  72971. };
  72972. };
  72973. /**
  72974. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  72975. * This RGBE texture needs to store the information as a panorama.
  72976. *
  72977. * More information on this format are available here:
  72978. * https://en.wikipedia.org/wiki/RGBE_image_format
  72979. *
  72980. * @param buffer The binary file stored in an array buffer.
  72981. * @param size The expected size of the extracted cubemap.
  72982. * @return The Cube Map information.
  72983. */
  72984. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  72985. var uint8array = new Uint8Array(buffer);
  72986. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  72987. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72988. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  72989. return cubeMapData;
  72990. };
  72991. /**
  72992. * Returns the pixels data extracted from an RGBE texture.
  72993. * This pixels will be stored left to right up to down in the R G B order in one array.
  72994. *
  72995. * More information on this format are available here:
  72996. * https://en.wikipedia.org/wiki/RGBE_image_format
  72997. *
  72998. * @param uint8array The binary file stored in an array buffer.
  72999. * @param hdrInfo The header information of the file.
  73000. * @return The pixels data in RGB right to left up to down order.
  73001. */
  73002. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  73003. // Keep for multi format supports.
  73004. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73005. };
  73006. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  73007. var num_scanlines = hdrInfo.height;
  73008. var scanline_width = hdrInfo.width;
  73009. var a, b, c, d, count;
  73010. var dataIndex = hdrInfo.dataPosition;
  73011. var index = 0, endIndex = 0, i = 0;
  73012. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  73013. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  73014. // 3 channels of 4 bytes per pixel in float.
  73015. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  73016. var resultArray = new Float32Array(resultBuffer);
  73017. // read in each successive scanline
  73018. while (num_scanlines > 0) {
  73019. a = uint8array[dataIndex++];
  73020. b = uint8array[dataIndex++];
  73021. c = uint8array[dataIndex++];
  73022. d = uint8array[dataIndex++];
  73023. if (a != 2 || b != 2 || (c & 0x80)) {
  73024. // this file is not run length encoded
  73025. throw "HDR Bad header format, not RLE";
  73026. }
  73027. if (((c << 8) | d) != scanline_width) {
  73028. throw "HDR Bad header format, wrong scan line width";
  73029. }
  73030. index = 0;
  73031. // read each of the four channels for the scanline into the buffer
  73032. for (i = 0; i < 4; i++) {
  73033. endIndex = (i + 1) * scanline_width;
  73034. while (index < endIndex) {
  73035. a = uint8array[dataIndex++];
  73036. b = uint8array[dataIndex++];
  73037. if (a > 128) {
  73038. // a run of the same value
  73039. count = a - 128;
  73040. if ((count == 0) || (count > endIndex - index)) {
  73041. throw "HDR Bad Format, bad scanline data (run)";
  73042. }
  73043. while (count-- > 0) {
  73044. scanLineArray[index++] = b;
  73045. }
  73046. }
  73047. else {
  73048. // a non-run
  73049. count = a;
  73050. if ((count == 0) || (count > endIndex - index)) {
  73051. throw "HDR Bad Format, bad scanline data (non-run)";
  73052. }
  73053. scanLineArray[index++] = b;
  73054. if (--count > 0) {
  73055. for (var j = 0; j < count; j++) {
  73056. scanLineArray[index++] = uint8array[dataIndex++];
  73057. }
  73058. }
  73059. }
  73060. }
  73061. }
  73062. // now convert data from buffer into floats
  73063. for (i = 0; i < scanline_width; i++) {
  73064. a = scanLineArray[i];
  73065. b = scanLineArray[i + scanline_width];
  73066. c = scanLineArray[i + 2 * scanline_width];
  73067. d = scanLineArray[i + 3 * scanline_width];
  73068. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  73069. }
  73070. num_scanlines--;
  73071. }
  73072. return resultArray;
  73073. };
  73074. return HDRTools;
  73075. }());
  73076. BABYLON.HDRTools = HDRTools;
  73077. })(BABYLON || (BABYLON = {}));
  73078. //# sourceMappingURL=babylon.hdr.js.map
  73079. var BABYLON;
  73080. (function (BABYLON) {
  73081. /**
  73082. * This represents a texture coming from an HDR input.
  73083. *
  73084. * The only supported format is currently panorama picture stored in RGBE format.
  73085. * Example of such files can be found on HDRLib: http://hdrlib.com/
  73086. */
  73087. var HDRCubeTexture = /** @class */ (function (_super) {
  73088. __extends(HDRCubeTexture, _super);
  73089. /**
  73090. * Instantiates an HDRTexture from the following parameters.
  73091. *
  73092. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  73093. * @param scene The scene the texture will be used in
  73094. * @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.
  73095. * @param noMipmap Forces to not generate the mipmap if true
  73096. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  73097. * @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)
  73098. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  73099. */
  73100. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  73101. if (noMipmap === void 0) { noMipmap = false; }
  73102. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73103. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73104. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73105. if (onLoad === void 0) { onLoad = null; }
  73106. if (onError === void 0) { onError = null; }
  73107. var _this = _super.call(this, scene) || this;
  73108. _this._useInGammaSpace = false;
  73109. _this._generateHarmonics = true;
  73110. _this._isBABYLONPreprocessed = false;
  73111. _this._onLoad = null;
  73112. _this._onError = null;
  73113. /**
  73114. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  73115. */
  73116. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  73117. /**
  73118. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  73119. * This is usefull at run time to apply the good shader.
  73120. */
  73121. _this.isPMREM = false;
  73122. _this._isBlocking = true;
  73123. /**
  73124. * Gets or sets the center of the bounding box associated with the cube texture
  73125. * It must define where the camera used to render the texture was set
  73126. */
  73127. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  73128. if (!url) {
  73129. return _this;
  73130. }
  73131. _this.name = url;
  73132. _this.url = url;
  73133. _this.hasAlpha = false;
  73134. _this.isCube = true;
  73135. _this._textureMatrix = BABYLON.Matrix.Identity();
  73136. _this._onLoad = onLoad;
  73137. _this._onError = onError;
  73138. _this.gammaSpace = false;
  73139. var caps = scene.getEngine().getCaps();
  73140. if (size) {
  73141. _this._isBABYLONPreprocessed = false;
  73142. _this._noMipmap = noMipmap;
  73143. _this._size = size;
  73144. _this._useInGammaSpace = useInGammaSpace;
  73145. _this._usePMREMGenerator = usePMREMGenerator &&
  73146. caps.textureLOD &&
  73147. caps.textureFloat &&
  73148. !_this._useInGammaSpace;
  73149. }
  73150. else {
  73151. _this._isBABYLONPreprocessed = true;
  73152. _this._noMipmap = false;
  73153. _this._useInGammaSpace = false;
  73154. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  73155. !_this._useInGammaSpace;
  73156. }
  73157. _this.isPMREM = _this._usePMREMGenerator;
  73158. _this._texture = _this._getFromCache(url, _this._noMipmap);
  73159. if (!_this._texture) {
  73160. if (!scene.useDelayedTextureLoading) {
  73161. _this.loadTexture();
  73162. }
  73163. else {
  73164. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  73165. }
  73166. }
  73167. return _this;
  73168. }
  73169. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  73170. /**
  73171. * Gets wether or not the texture is blocking during loading.
  73172. */
  73173. get: function () {
  73174. return this._isBlocking;
  73175. },
  73176. /**
  73177. * Sets wether or not the texture is blocking during loading.
  73178. */
  73179. set: function (value) {
  73180. this._isBlocking = value;
  73181. },
  73182. enumerable: true,
  73183. configurable: true
  73184. });
  73185. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  73186. get: function () {
  73187. return this._boundingBoxSize;
  73188. },
  73189. /**
  73190. * Gets or sets the size of the bounding box associated with the cube texture
  73191. * When defined, the cubemap will switch to local mode
  73192. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  73193. * @example https://www.babylonjs-playground.com/#RNASML
  73194. */
  73195. set: function (value) {
  73196. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  73197. return;
  73198. }
  73199. this._boundingBoxSize = value;
  73200. var scene = this.getScene();
  73201. if (scene) {
  73202. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  73203. }
  73204. },
  73205. enumerable: true,
  73206. configurable: true
  73207. });
  73208. /**
  73209. * Occurs when the file is a preprocessed .babylon.hdr file.
  73210. */
  73211. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  73212. var _this = this;
  73213. var mipLevels = 0;
  73214. var floatArrayView = null;
  73215. var scene = this.getScene();
  73216. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  73217. var mips = new Array();
  73218. if (!floatArrayView) {
  73219. return mips;
  73220. }
  73221. var startIndex = 30;
  73222. for (var level = 0; level < mipLevels; level++) {
  73223. mips.push([]);
  73224. // Fill each pixel of the mip level.
  73225. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  73226. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73227. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  73228. mips[level].push(faceData);
  73229. startIndex += faceSize;
  73230. }
  73231. }
  73232. return mips;
  73233. } : null;
  73234. var callback = function (buffer) {
  73235. var scene = _this.getScene();
  73236. if (!scene) {
  73237. return null;
  73238. }
  73239. // Create Native Array Views
  73240. var intArrayView = new Int32Array(buffer);
  73241. floatArrayView = new Float32Array(buffer);
  73242. // Fill header.
  73243. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  73244. _this._size = intArrayView[1]; // CubeMap max mip face size.
  73245. // Update Texture Information.
  73246. if (!_this._texture) {
  73247. return null;
  73248. }
  73249. _this._texture.updateSize(_this._size, _this._size);
  73250. // Fill polynomial information.
  73251. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  73252. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  73253. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  73254. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  73255. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  73256. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  73257. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  73258. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  73259. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  73260. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  73261. _this.sphericalPolynomial = sphericalPolynomial;
  73262. // Fill pixel data.
  73263. mipLevels = intArrayView[29]; // Number of mip levels.
  73264. var startIndex = 30;
  73265. var data = [];
  73266. var faceSize = Math.pow(_this._size, 2) * 3;
  73267. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73268. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  73269. startIndex += faceSize;
  73270. }
  73271. var results = [];
  73272. var byteArray = null;
  73273. // Push each faces.
  73274. for (var k = 0; k < 6; k++) {
  73275. var dataFace = null;
  73276. // To be deprecated.
  73277. if (version === 1) {
  73278. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  73279. dataFace = data[j];
  73280. }
  73281. // If special cases.
  73282. if (!mipmapGenerator && dataFace) {
  73283. if (!scene.getEngine().getCaps().textureFloat) {
  73284. // 3 channels of 1 bytes per pixel in bytes.
  73285. var byteBuffer = new ArrayBuffer(faceSize);
  73286. byteArray = new Uint8Array(byteBuffer);
  73287. }
  73288. for (var i = 0; i < _this._size * _this._size; i++) {
  73289. // Put in gamma space if requested.
  73290. if (_this._useInGammaSpace) {
  73291. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73292. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73293. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73294. }
  73295. // Convert to int texture for fallback.
  73296. if (byteArray) {
  73297. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73298. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73299. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73300. // May use luminance instead if the result is not accurate.
  73301. var max = Math.max(Math.max(r, g), b);
  73302. if (max > 255) {
  73303. var scale = 255 / max;
  73304. r *= scale;
  73305. g *= scale;
  73306. b *= scale;
  73307. }
  73308. byteArray[(i * 3) + 0] = r;
  73309. byteArray[(i * 3) + 1] = g;
  73310. byteArray[(i * 3) + 2] = b;
  73311. }
  73312. }
  73313. }
  73314. // Fill the array accordingly.
  73315. if (byteArray) {
  73316. results.push(byteArray);
  73317. }
  73318. else {
  73319. results.push(dataFace);
  73320. }
  73321. }
  73322. return results;
  73323. };
  73324. if (scene) {
  73325. 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);
  73326. }
  73327. };
  73328. /**
  73329. * Occurs when the file is raw .hdr file.
  73330. */
  73331. HDRCubeTexture.prototype.loadHDRTexture = function () {
  73332. var _this = this;
  73333. var callback = function (buffer) {
  73334. var scene = _this.getScene();
  73335. if (!scene) {
  73336. return null;
  73337. }
  73338. // Extract the raw linear data.
  73339. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  73340. // Generate harmonics if needed.
  73341. if (_this._generateHarmonics) {
  73342. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  73343. _this.sphericalPolynomial = sphericalPolynomial;
  73344. }
  73345. var results = [];
  73346. var byteArray = null;
  73347. // Push each faces.
  73348. for (var j = 0; j < 6; j++) {
  73349. // Create uintarray fallback.
  73350. if (!scene.getEngine().getCaps().textureFloat) {
  73351. // 3 channels of 1 bytes per pixel in bytes.
  73352. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  73353. byteArray = new Uint8Array(byteBuffer);
  73354. }
  73355. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  73356. // If special cases.
  73357. if (_this._useInGammaSpace || byteArray) {
  73358. for (var i = 0; i < _this._size * _this._size; i++) {
  73359. // Put in gamma space if requested.
  73360. if (_this._useInGammaSpace) {
  73361. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  73362. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  73363. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  73364. }
  73365. // Convert to int texture for fallback.
  73366. if (byteArray) {
  73367. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  73368. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  73369. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  73370. // May use luminance instead if the result is not accurate.
  73371. var max = Math.max(Math.max(r, g), b);
  73372. if (max > 255) {
  73373. var scale = 255 / max;
  73374. r *= scale;
  73375. g *= scale;
  73376. b *= scale;
  73377. }
  73378. byteArray[(i * 3) + 0] = r;
  73379. byteArray[(i * 3) + 1] = g;
  73380. byteArray[(i * 3) + 2] = b;
  73381. }
  73382. }
  73383. }
  73384. if (byteArray) {
  73385. results.push(byteArray);
  73386. }
  73387. else {
  73388. results.push(dataFace);
  73389. }
  73390. }
  73391. return results;
  73392. };
  73393. var mipmapGenerator = null;
  73394. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  73395. // if (!this._noMipmap &&
  73396. // this._usePMREMGenerator) {
  73397. // mipmapGenerator = (data: ArrayBufferView[]) => {
  73398. // // Custom setup of the generator matching with the PBR shader values.
  73399. // var generator = new BABYLON.PMREMGenerator(data,
  73400. // this._size,
  73401. // this._size,
  73402. // 0,
  73403. // 3,
  73404. // this.getScene().getEngine().getCaps().textureFloat,
  73405. // 2048,
  73406. // 0.25,
  73407. // false,
  73408. // true);
  73409. // return generator.filterCubeMap();
  73410. // };
  73411. // }
  73412. var scene = this.getScene();
  73413. if (scene) {
  73414. 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);
  73415. }
  73416. };
  73417. /**
  73418. * Starts the loading process of the texture.
  73419. */
  73420. HDRCubeTexture.prototype.loadTexture = function () {
  73421. if (this._isBABYLONPreprocessed) {
  73422. this.loadBabylonTexture();
  73423. }
  73424. else {
  73425. this.loadHDRTexture();
  73426. }
  73427. };
  73428. HDRCubeTexture.prototype.clone = function () {
  73429. var scene = this.getScene();
  73430. if (!scene) {
  73431. return this;
  73432. }
  73433. var size = (this._isBABYLONPreprocessed ? null : this._size);
  73434. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  73435. // Base texture
  73436. newTexture.level = this.level;
  73437. newTexture.wrapU = this.wrapU;
  73438. newTexture.wrapV = this.wrapV;
  73439. newTexture.coordinatesIndex = this.coordinatesIndex;
  73440. newTexture.coordinatesMode = this.coordinatesMode;
  73441. return newTexture;
  73442. };
  73443. // Methods
  73444. HDRCubeTexture.prototype.delayLoad = function () {
  73445. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  73446. return;
  73447. }
  73448. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  73449. this._texture = this._getFromCache(this.url, this._noMipmap);
  73450. if (!this._texture) {
  73451. this.loadTexture();
  73452. }
  73453. };
  73454. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  73455. return this._textureMatrix;
  73456. };
  73457. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  73458. this._textureMatrix = value;
  73459. };
  73460. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  73461. var texture = null;
  73462. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  73463. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  73464. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  73465. texture.name = parsedTexture.name;
  73466. texture.hasAlpha = parsedTexture.hasAlpha;
  73467. texture.level = parsedTexture.level;
  73468. texture.coordinatesMode = parsedTexture.coordinatesMode;
  73469. texture.isBlocking = parsedTexture.isBlocking;
  73470. }
  73471. if (texture) {
  73472. if (parsedTexture.boundingBoxPosition) {
  73473. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  73474. }
  73475. if (parsedTexture.boundingBoxSize) {
  73476. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  73477. }
  73478. }
  73479. return texture;
  73480. };
  73481. HDRCubeTexture.prototype.serialize = function () {
  73482. if (!this.name) {
  73483. return null;
  73484. }
  73485. var serializationObject = {};
  73486. serializationObject.name = this.name;
  73487. serializationObject.hasAlpha = this.hasAlpha;
  73488. serializationObject.isCube = true;
  73489. serializationObject.level = this.level;
  73490. serializationObject.size = this._size;
  73491. serializationObject.coordinatesMode = this.coordinatesMode;
  73492. serializationObject.useInGammaSpace = this._useInGammaSpace;
  73493. serializationObject.generateHarmonics = this._generateHarmonics;
  73494. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  73495. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  73496. serializationObject.customType = "BABYLON.HDRCubeTexture";
  73497. serializationObject.noMipmap = this._noMipmap;
  73498. serializationObject.isBlocking = this._isBlocking;
  73499. return serializationObject;
  73500. };
  73501. /**
  73502. * Saves as a file the data contained in the texture in a binary format.
  73503. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73504. * as the spherical used in the lighting.
  73505. * @param url The HDR file url.
  73506. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73507. * @param onError Method called if any error happens during download.
  73508. * @return The packed binary data.
  73509. */
  73510. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  73511. if (onError === void 0) { onError = null; }
  73512. var callback = function (buffer) {
  73513. var data = new Blob([buffer], { type: 'application/octet-stream' });
  73514. // Returns a URL you can use as a href.
  73515. var objUrl = window.URL.createObjectURL(data);
  73516. // Simulates a link to it and click to dowload.
  73517. var a = document.createElement("a");
  73518. document.body.appendChild(a);
  73519. a.style.display = "none";
  73520. a.href = objUrl;
  73521. a.download = "envmap.babylon.hdr";
  73522. a.click();
  73523. };
  73524. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  73525. };
  73526. /**
  73527. * Serializes the data contained in the texture in a binary format.
  73528. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  73529. * as the spherical used in the lighting.
  73530. * @param url The HDR file url.
  73531. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  73532. * @param onError Method called if any error happens during download.
  73533. * @return The packed binary data.
  73534. */
  73535. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  73536. if (onError === void 0) { onError = null; }
  73537. // Needs the url tho create the texture.
  73538. if (!url) {
  73539. return;
  73540. }
  73541. // Check Power of two size.
  73542. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  73543. return;
  73544. }
  73545. // Coming Back in 3.x.
  73546. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  73547. };
  73548. HDRCubeTexture._facesMapping = [
  73549. "right",
  73550. "left",
  73551. "up",
  73552. "down",
  73553. "front",
  73554. "back"
  73555. ];
  73556. return HDRCubeTexture;
  73557. }(BABYLON.BaseTexture));
  73558. BABYLON.HDRCubeTexture = HDRCubeTexture;
  73559. })(BABYLON || (BABYLON = {}));
  73560. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  73561. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  73562. // Huge respect for a such great lib.
  73563. // Earcut license:
  73564. // Copyright (c) 2016, Mapbox
  73565. //
  73566. // Permission to use, copy, modify, and/or distribute this software for any purpose
  73567. // with or without fee is hereby granted, provided that the above copyright notice
  73568. // and this permission notice appear in all copies.
  73569. //
  73570. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  73571. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  73572. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  73573. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  73574. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  73575. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  73576. // THIS SOFTWARE.
  73577. var Earcut;
  73578. (function (Earcut) {
  73579. /**
  73580. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  73581. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  73582. * @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).
  73583. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  73584. */
  73585. function earcut(data, holeIndices, dim) {
  73586. dim = dim || 2;
  73587. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  73588. if (!outerNode)
  73589. return triangles;
  73590. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  73591. if (hasHoles)
  73592. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  73593. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  73594. if (data.length > 80 * dim) {
  73595. minX = maxX = data[0];
  73596. minY = maxY = data[1];
  73597. for (var i = dim; i < outerLen; i += dim) {
  73598. x = data[i];
  73599. y = data[i + 1];
  73600. if (x < minX)
  73601. minX = x;
  73602. if (y < minY)
  73603. minY = y;
  73604. if (x > maxX)
  73605. maxX = x;
  73606. if (y > maxY)
  73607. maxY = y;
  73608. }
  73609. // minX, minY and size are later used to transform coords into integers for z-order calculation
  73610. size = Math.max(maxX - minX, maxY - minY);
  73611. }
  73612. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  73613. return triangles;
  73614. }
  73615. Earcut.earcut = earcut;
  73616. var Node = /** @class */ (function () {
  73617. function Node(i, x, y) {
  73618. this.i = i;
  73619. this.x = x;
  73620. this.y = y;
  73621. this.prev = null;
  73622. this.next = null;
  73623. this.z = null;
  73624. this.prevZ = null;
  73625. this.nextZ = null;
  73626. this.steiner = false;
  73627. }
  73628. return Node;
  73629. }());
  73630. // create a circular doubly linked list from polygon points in the specified winding order
  73631. function linkedList(data, start, end, dim, clockwise) {
  73632. var i, last = null;
  73633. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  73634. for (i = start; i < end; i += dim)
  73635. last = insertNode(i, data[i], data[i + 1], last);
  73636. }
  73637. else {
  73638. for (i = end - dim; i >= start; i -= dim)
  73639. last = insertNode(i, data[i], data[i + 1], last);
  73640. }
  73641. if (last && equals(last, last.next)) {
  73642. removeNode(last);
  73643. last = last.next;
  73644. }
  73645. return last;
  73646. }
  73647. // eliminate colinear or duplicate points
  73648. function filterPoints(start, end) {
  73649. if (!start)
  73650. return start;
  73651. if (!end)
  73652. end = start;
  73653. var p = start, again;
  73654. do {
  73655. again = false;
  73656. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  73657. removeNode(p);
  73658. p = end = p.prev;
  73659. if (p === p.next)
  73660. return undefined;
  73661. again = true;
  73662. }
  73663. else {
  73664. p = p.next;
  73665. }
  73666. } while (again || p !== end);
  73667. return end;
  73668. }
  73669. // main ear slicing loop which triangulates a polygon (given as a linked list)
  73670. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  73671. if (!ear)
  73672. return;
  73673. // interlink polygon nodes in z-order
  73674. if (!pass && size)
  73675. indexCurve(ear, minX, minY, size);
  73676. var stop = ear, prev, next;
  73677. // iterate through ears, slicing them one by one
  73678. while (ear.prev !== ear.next) {
  73679. prev = ear.prev;
  73680. next = ear.next;
  73681. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  73682. // cut off the triangle
  73683. triangles.push(prev.i / dim);
  73684. triangles.push(ear.i / dim);
  73685. triangles.push(next.i / dim);
  73686. removeNode(ear);
  73687. // skipping the next vertice leads to less sliver triangles
  73688. ear = next.next;
  73689. stop = next.next;
  73690. continue;
  73691. }
  73692. ear = next;
  73693. // if we looped through the whole remaining polygon and can't find any more ears
  73694. if (ear === stop) {
  73695. // try filtering points and slicing again
  73696. if (!pass) {
  73697. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  73698. // if this didn't work, try curing all small self-intersections locally
  73699. }
  73700. else if (pass === 1) {
  73701. ear = cureLocalIntersections(ear, triangles, dim);
  73702. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  73703. // as a last resort, try splitting the remaining polygon into two
  73704. }
  73705. else if (pass === 2) {
  73706. splitEarcut(ear, triangles, dim, minX, minY, size);
  73707. }
  73708. break;
  73709. }
  73710. }
  73711. }
  73712. // check whether a polygon node forms a valid ear with adjacent nodes
  73713. function isEar(ear) {
  73714. var a = ear.prev, b = ear, c = ear.next;
  73715. if (area(a, b, c) >= 0)
  73716. return false; // reflex, can't be an ear
  73717. // now make sure we don't have other points inside the potential ear
  73718. var p = ear.next.next;
  73719. while (p !== ear.prev) {
  73720. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73721. area(p.prev, p, p.next) >= 0)
  73722. return false;
  73723. p = p.next;
  73724. }
  73725. return true;
  73726. }
  73727. function isEarHashed(ear, minX, minY, size) {
  73728. var a = ear.prev, b = ear, c = ear.next;
  73729. if (area(a, b, c) >= 0)
  73730. return false; // reflex, can't be an ear
  73731. // triangle bbox; min & max are calculated like this for speed
  73732. 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);
  73733. // z-order range for the current triangle bbox;
  73734. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  73735. // first look for points inside the triangle in increasing z-order
  73736. var p = ear.nextZ;
  73737. while (p && p.z <= maxZ) {
  73738. if (p !== ear.prev &&
  73739. p !== ear.next &&
  73740. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73741. area(p.prev, p, p.next) >= 0)
  73742. return false;
  73743. p = p.nextZ;
  73744. }
  73745. // then look for points in decreasing z-order
  73746. p = ear.prevZ;
  73747. while (p && p.z >= minZ) {
  73748. if (p !== ear.prev &&
  73749. p !== ear.next &&
  73750. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73751. area(p.prev, p, p.next) >= 0)
  73752. return false;
  73753. p = p.prevZ;
  73754. }
  73755. return true;
  73756. }
  73757. // go through all polygon nodes and cure small local self-intersections
  73758. function cureLocalIntersections(start, triangles, dim) {
  73759. var p = start;
  73760. do {
  73761. var a = p.prev, b = p.next.next;
  73762. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  73763. triangles.push(a.i / dim);
  73764. triangles.push(p.i / dim);
  73765. triangles.push(b.i / dim);
  73766. // remove two nodes involved
  73767. removeNode(p);
  73768. removeNode(p.next);
  73769. p = start = b;
  73770. }
  73771. p = p.next;
  73772. } while (p !== start);
  73773. return p;
  73774. }
  73775. // try splitting polygon into two and triangulate them independently
  73776. function splitEarcut(start, triangles, dim, minX, minY, size) {
  73777. // look for a valid diagonal that divides the polygon into two
  73778. var a = start;
  73779. do {
  73780. var b = a.next.next;
  73781. while (b !== a.prev) {
  73782. if (a.i !== b.i && isValidDiagonal(a, b)) {
  73783. // split the polygon in two by the diagonal
  73784. var c = splitPolygon(a, b);
  73785. // filter colinear points around the cuts
  73786. a = filterPoints(a, a.next);
  73787. c = filterPoints(c, c.next);
  73788. // run earcut on each half
  73789. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  73790. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  73791. return;
  73792. }
  73793. b = b.next;
  73794. }
  73795. a = a.next;
  73796. } while (a !== start);
  73797. }
  73798. // link every hole into the outer loop, producing a single-ring polygon without holes
  73799. function eliminateHoles(data, holeIndices, outerNode, dim) {
  73800. var queue = [], i, len, start, end, list;
  73801. for (i = 0, len = holeIndices.length; i < len; i++) {
  73802. start = holeIndices[i] * dim;
  73803. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73804. list = linkedList(data, start, end, dim, false);
  73805. if (list === list.next)
  73806. list.steiner = true;
  73807. queue.push(getLeftmost(list));
  73808. }
  73809. queue.sort(compareX);
  73810. // process holes from left to right
  73811. for (i = 0; i < queue.length; i++) {
  73812. eliminateHole(queue[i], outerNode);
  73813. outerNode = filterPoints(outerNode, outerNode.next);
  73814. }
  73815. return outerNode;
  73816. }
  73817. function compareX(a, b) {
  73818. return a.x - b.x;
  73819. }
  73820. // find a bridge between vertices that connects hole with an outer ring and and link it
  73821. function eliminateHole(hole, outerNode) {
  73822. outerNode = findHoleBridge(hole, outerNode);
  73823. if (outerNode) {
  73824. var b = splitPolygon(outerNode, hole);
  73825. filterPoints(b, b.next);
  73826. }
  73827. }
  73828. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  73829. function findHoleBridge(hole, outerNode) {
  73830. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  73831. // find a segment intersected by a ray from the hole's leftmost point to the left;
  73832. // segment's endpoint with lesser x will be potential connection point
  73833. do {
  73834. if (hy <= p.y && hy >= p.next.y) {
  73835. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  73836. if (x <= hx && x > qx) {
  73837. qx = x;
  73838. if (x === hx) {
  73839. if (hy === p.y)
  73840. return p;
  73841. if (hy === p.next.y)
  73842. return p.next;
  73843. }
  73844. m = p.x < p.next.x ? p : p.next;
  73845. }
  73846. }
  73847. p = p.next;
  73848. } while (p !== outerNode);
  73849. if (!m)
  73850. return null;
  73851. if (hx === qx)
  73852. return m.prev; // hole touches outer segment; pick lower endpoint
  73853. // look for points inside the triangle of hole point, segment intersection and endpoint;
  73854. // if there are no points found, we have a valid connection;
  73855. // otherwise choose the point of the minimum angle with the ray as connection point
  73856. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  73857. p = m.next;
  73858. while (p !== stop) {
  73859. if (hx >= p.x &&
  73860. p.x >= mx &&
  73861. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  73862. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  73863. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  73864. m = p;
  73865. tanMin = tan;
  73866. }
  73867. }
  73868. p = p.next;
  73869. }
  73870. return m;
  73871. }
  73872. // interlink polygon nodes in z-order
  73873. function indexCurve(start, minX, minY, size) {
  73874. var p = start;
  73875. do {
  73876. if (p.z === null)
  73877. p.z = zOrder(p.x, p.y, minX, minY, size);
  73878. p.prevZ = p.prev;
  73879. p.nextZ = p.next;
  73880. p = p.next;
  73881. } while (p !== start);
  73882. p.prevZ.nextZ = null;
  73883. p.prevZ = null;
  73884. sortLinked(p);
  73885. }
  73886. // Simon Tatham's linked list merge sort algorithm
  73887. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  73888. function sortLinked(list) {
  73889. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  73890. do {
  73891. p = list;
  73892. list = null;
  73893. tail = null;
  73894. numMerges = 0;
  73895. while (p) {
  73896. numMerges++;
  73897. q = p;
  73898. pSize = 0;
  73899. for (i = 0; i < inSize; i++) {
  73900. pSize++;
  73901. q = q.nextZ;
  73902. if (!q)
  73903. break;
  73904. }
  73905. qSize = inSize;
  73906. while (pSize > 0 || (qSize > 0 && q)) {
  73907. if (pSize === 0) {
  73908. e = q;
  73909. q = q.nextZ;
  73910. qSize--;
  73911. }
  73912. else if (qSize === 0 || !q) {
  73913. e = p;
  73914. p = p.nextZ;
  73915. pSize--;
  73916. }
  73917. else if (p.z <= q.z) {
  73918. e = p;
  73919. p = p.nextZ;
  73920. pSize--;
  73921. }
  73922. else {
  73923. e = q;
  73924. q = q.nextZ;
  73925. qSize--;
  73926. }
  73927. if (tail)
  73928. tail.nextZ = e;
  73929. else
  73930. list = e;
  73931. e.prevZ = tail;
  73932. tail = e;
  73933. }
  73934. p = q;
  73935. }
  73936. tail.nextZ = null;
  73937. inSize *= 2;
  73938. } while (numMerges > 1);
  73939. return list;
  73940. }
  73941. // z-order of a point given coords and size of the data bounding box
  73942. function zOrder(x, y, minX, minY, size) {
  73943. // coords are transformed into non-negative 15-bit integer range
  73944. x = 32767 * (x - minX) / size;
  73945. y = 32767 * (y - minY) / size;
  73946. x = (x | (x << 8)) & 0x00FF00FF;
  73947. x = (x | (x << 4)) & 0x0F0F0F0F;
  73948. x = (x | (x << 2)) & 0x33333333;
  73949. x = (x | (x << 1)) & 0x55555555;
  73950. y = (y | (y << 8)) & 0x00FF00FF;
  73951. y = (y | (y << 4)) & 0x0F0F0F0F;
  73952. y = (y | (y << 2)) & 0x33333333;
  73953. y = (y | (y << 1)) & 0x55555555;
  73954. return x | (y << 1);
  73955. }
  73956. // find the leftmost node of a polygon ring
  73957. function getLeftmost(start) {
  73958. var p = start, leftmost = start;
  73959. do {
  73960. if (p.x < leftmost.x)
  73961. leftmost = p;
  73962. p = p.next;
  73963. } while (p !== start);
  73964. return leftmost;
  73965. }
  73966. // check if a point lies within a convex triangle
  73967. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  73968. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  73969. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  73970. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  73971. }
  73972. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  73973. function isValidDiagonal(a, b) {
  73974. return a.next.i !== b.i &&
  73975. a.prev.i !== b.i &&
  73976. !intersectsPolygon(a, b) &&
  73977. locallyInside(a, b) &&
  73978. locallyInside(b, a) &&
  73979. middleInside(a, b);
  73980. }
  73981. // signed area of a triangle
  73982. function area(p, q, r) {
  73983. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  73984. }
  73985. // check if two points are equal
  73986. function equals(p1, p2) {
  73987. return p1.x === p2.x && p1.y === p2.y;
  73988. }
  73989. // check if two segments intersect
  73990. function intersects(p1, q1, p2, q2) {
  73991. if ((equals(p1, q1) && equals(p2, q2)) ||
  73992. (equals(p1, q2) && equals(p2, q1)))
  73993. return true;
  73994. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  73995. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  73996. }
  73997. // check if a polygon diagonal intersects any polygon segments
  73998. function intersectsPolygon(a, b) {
  73999. var p = a;
  74000. do {
  74001. if (p.i !== a.i &&
  74002. p.next.i !== a.i &&
  74003. p.i !== b.i &&
  74004. p.next.i !== b.i &&
  74005. intersects(p, p.next, a, b))
  74006. return true;
  74007. p = p.next;
  74008. } while (p !== a);
  74009. return false;
  74010. }
  74011. // check if a polygon diagonal is locally inside the polygon
  74012. function locallyInside(a, b) {
  74013. return area(a.prev, a, a.next) < 0
  74014. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  74015. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  74016. }
  74017. // check if the middle point of a polygon diagonal is inside the polygon
  74018. function middleInside(a, b) {
  74019. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  74020. do {
  74021. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  74022. inside = !inside;
  74023. p = p.next;
  74024. } while (p !== a);
  74025. return inside;
  74026. }
  74027. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  74028. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  74029. function splitPolygon(a, b) {
  74030. 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;
  74031. a.next = b;
  74032. b.prev = a;
  74033. a2.next = an;
  74034. an.prev = a2;
  74035. b2.next = a2;
  74036. a2.prev = b2;
  74037. bp.next = b2;
  74038. b2.prev = bp;
  74039. return b2;
  74040. }
  74041. // create a node and optionally link it with previous one (in a circular doubly linked list)
  74042. function insertNode(i, x, y, last) {
  74043. var p = new Node(i, x, y);
  74044. if (!last) {
  74045. p.prev = p;
  74046. p.next = p;
  74047. }
  74048. else {
  74049. p.next = last.next;
  74050. p.prev = last;
  74051. last.next.prev = p;
  74052. last.next = p;
  74053. }
  74054. return p;
  74055. }
  74056. function removeNode(p) {
  74057. p.next.prev = p.prev;
  74058. p.prev.next = p.next;
  74059. if (p.prevZ)
  74060. p.prevZ.nextZ = p.nextZ;
  74061. if (p.nextZ)
  74062. p.nextZ.prevZ = p.prevZ;
  74063. }
  74064. /**
  74065. * return a percentage difference between the polygon area and its triangulation area;
  74066. * used to verify correctness of triangulation
  74067. */
  74068. function deviation(data, holeIndices, dim, triangles) {
  74069. var hasHoles = holeIndices && holeIndices.length;
  74070. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  74071. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  74072. if (hasHoles) {
  74073. for (var i = 0, len = holeIndices.length; i < len; i++) {
  74074. var start = holeIndices[i] * dim;
  74075. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74076. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  74077. }
  74078. }
  74079. var trianglesArea = 0;
  74080. for (i = 0; i < triangles.length; i += 3) {
  74081. var a = triangles[i] * dim;
  74082. var b = triangles[i + 1] * dim;
  74083. var c = triangles[i + 2] * dim;
  74084. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  74085. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  74086. }
  74087. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  74088. }
  74089. Earcut.deviation = deviation;
  74090. ;
  74091. function signedArea(data, start, end, dim) {
  74092. var sum = 0;
  74093. for (var i = start, j = end - dim; i < end; i += dim) {
  74094. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  74095. j = i;
  74096. }
  74097. return sum;
  74098. }
  74099. /**
  74100. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  74101. */
  74102. function flatten(data) {
  74103. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  74104. for (var i = 0; i < data.length; i++) {
  74105. for (var j = 0; j < data[i].length; j++) {
  74106. for (var d = 0; d < dim; d++)
  74107. result.vertices.push(data[i][j][d]);
  74108. }
  74109. if (i > 0) {
  74110. holeIndex += data[i - 1].length;
  74111. result.holes.push(holeIndex);
  74112. }
  74113. }
  74114. return result;
  74115. }
  74116. Earcut.flatten = flatten;
  74117. ;
  74118. })(Earcut || (Earcut = {}));
  74119. //# sourceMappingURL=babylon.earcut.js.map
  74120. var BABYLON;
  74121. (function (BABYLON) {
  74122. var IndexedVector2 = /** @class */ (function (_super) {
  74123. __extends(IndexedVector2, _super);
  74124. function IndexedVector2(original, index) {
  74125. var _this = _super.call(this, original.x, original.y) || this;
  74126. _this.index = index;
  74127. return _this;
  74128. }
  74129. return IndexedVector2;
  74130. }(BABYLON.Vector2));
  74131. var PolygonPoints = /** @class */ (function () {
  74132. function PolygonPoints() {
  74133. this.elements = new Array();
  74134. }
  74135. PolygonPoints.prototype.add = function (originalPoints) {
  74136. var _this = this;
  74137. var result = new Array();
  74138. originalPoints.forEach(function (point) {
  74139. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  74140. var newPoint = new IndexedVector2(point, _this.elements.length);
  74141. result.push(newPoint);
  74142. _this.elements.push(newPoint);
  74143. }
  74144. });
  74145. return result;
  74146. };
  74147. PolygonPoints.prototype.computeBounds = function () {
  74148. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74149. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74150. this.elements.forEach(function (point) {
  74151. // x
  74152. if (point.x < lmin.x) {
  74153. lmin.x = point.x;
  74154. }
  74155. else if (point.x > lmax.x) {
  74156. lmax.x = point.x;
  74157. }
  74158. // y
  74159. if (point.y < lmin.y) {
  74160. lmin.y = point.y;
  74161. }
  74162. else if (point.y > lmax.y) {
  74163. lmax.y = point.y;
  74164. }
  74165. });
  74166. return {
  74167. min: lmin,
  74168. max: lmax,
  74169. width: lmax.x - lmin.x,
  74170. height: lmax.y - lmin.y
  74171. };
  74172. };
  74173. return PolygonPoints;
  74174. }());
  74175. var Polygon = /** @class */ (function () {
  74176. function Polygon() {
  74177. }
  74178. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  74179. return [
  74180. new BABYLON.Vector2(xmin, ymin),
  74181. new BABYLON.Vector2(xmax, ymin),
  74182. new BABYLON.Vector2(xmax, ymax),
  74183. new BABYLON.Vector2(xmin, ymax)
  74184. ];
  74185. };
  74186. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  74187. if (cx === void 0) { cx = 0; }
  74188. if (cy === void 0) { cy = 0; }
  74189. if (numberOfSides === void 0) { numberOfSides = 32; }
  74190. var result = new Array();
  74191. var angle = 0;
  74192. var increment = (Math.PI * 2) / numberOfSides;
  74193. for (var i = 0; i < numberOfSides; i++) {
  74194. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  74195. angle -= increment;
  74196. }
  74197. return result;
  74198. };
  74199. Polygon.Parse = function (input) {
  74200. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  74201. var i, result = [];
  74202. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  74203. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  74204. }
  74205. return result;
  74206. };
  74207. Polygon.StartingAt = function (x, y) {
  74208. return BABYLON.Path2.StartingAt(x, y);
  74209. };
  74210. return Polygon;
  74211. }());
  74212. BABYLON.Polygon = Polygon;
  74213. var PolygonMeshBuilder = /** @class */ (function () {
  74214. function PolygonMeshBuilder(name, contours, scene) {
  74215. this._points = new PolygonPoints();
  74216. this._outlinepoints = new PolygonPoints();
  74217. this._holes = new Array();
  74218. this._epoints = new Array();
  74219. this._eholes = new Array();
  74220. this._name = name;
  74221. this._scene = scene;
  74222. var points;
  74223. if (contours instanceof BABYLON.Path2) {
  74224. points = contours.getPoints();
  74225. }
  74226. else {
  74227. points = contours;
  74228. }
  74229. this._addToepoint(points);
  74230. this._points.add(points);
  74231. this._outlinepoints.add(points);
  74232. }
  74233. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  74234. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  74235. var p = points_1[_i];
  74236. this._epoints.push(p.x, p.y);
  74237. }
  74238. };
  74239. PolygonMeshBuilder.prototype.addHole = function (hole) {
  74240. this._points.add(hole);
  74241. var holepoints = new PolygonPoints();
  74242. holepoints.add(hole);
  74243. this._holes.push(holepoints);
  74244. this._eholes.push(this._epoints.length / 2);
  74245. this._addToepoint(hole);
  74246. return this;
  74247. };
  74248. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  74249. var _this = this;
  74250. if (updatable === void 0) { updatable = false; }
  74251. if (depth === void 0) { depth = 0; }
  74252. var result = new BABYLON.Mesh(this._name, this._scene);
  74253. var normals = new Array();
  74254. var positions = new Array();
  74255. var uvs = new Array();
  74256. var bounds = this._points.computeBounds();
  74257. this._points.elements.forEach(function (p) {
  74258. normals.push(0, 1.0, 0);
  74259. positions.push(p.x, 0, p.y);
  74260. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  74261. });
  74262. var indices = new Array();
  74263. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  74264. for (var i = 0; i < res.length; i++) {
  74265. indices.push(res[i]);
  74266. }
  74267. if (depth > 0) {
  74268. var positionscount = (positions.length / 3); //get the current pointcount
  74269. this._points.elements.forEach(function (p) {
  74270. normals.push(0, -1.0, 0);
  74271. positions.push(p.x, -depth, p.y);
  74272. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  74273. });
  74274. var totalCount = indices.length;
  74275. for (var i = 0; i < totalCount; i += 3) {
  74276. var i0 = indices[i + 0];
  74277. var i1 = indices[i + 1];
  74278. var i2 = indices[i + 2];
  74279. indices.push(i2 + positionscount);
  74280. indices.push(i1 + positionscount);
  74281. indices.push(i0 + positionscount);
  74282. }
  74283. //Add the sides
  74284. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  74285. this._holes.forEach(function (hole) {
  74286. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  74287. });
  74288. }
  74289. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  74290. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  74291. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  74292. result.setIndices(indices);
  74293. return result;
  74294. };
  74295. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  74296. var StartIndex = positions.length / 3;
  74297. var ulength = 0;
  74298. for (var i = 0; i < points.elements.length; i++) {
  74299. var p = points.elements[i];
  74300. var p1;
  74301. if ((i + 1) > points.elements.length - 1) {
  74302. p1 = points.elements[0];
  74303. }
  74304. else {
  74305. p1 = points.elements[i + 1];
  74306. }
  74307. positions.push(p.x, 0, p.y);
  74308. positions.push(p.x, -depth, p.y);
  74309. positions.push(p1.x, 0, p1.y);
  74310. positions.push(p1.x, -depth, p1.y);
  74311. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  74312. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  74313. var v3 = v2.subtract(v1);
  74314. var v4 = new BABYLON.Vector3(0, 1, 0);
  74315. var vn = BABYLON.Vector3.Cross(v3, v4);
  74316. vn = vn.normalize();
  74317. uvs.push(ulength / bounds.width, 0);
  74318. uvs.push(ulength / bounds.width, 1);
  74319. ulength += v3.length();
  74320. uvs.push((ulength / bounds.width), 0);
  74321. uvs.push((ulength / bounds.width), 1);
  74322. if (!flip) {
  74323. normals.push(-vn.x, -vn.y, -vn.z);
  74324. normals.push(-vn.x, -vn.y, -vn.z);
  74325. normals.push(-vn.x, -vn.y, -vn.z);
  74326. normals.push(-vn.x, -vn.y, -vn.z);
  74327. indices.push(StartIndex);
  74328. indices.push(StartIndex + 1);
  74329. indices.push(StartIndex + 2);
  74330. indices.push(StartIndex + 1);
  74331. indices.push(StartIndex + 3);
  74332. indices.push(StartIndex + 2);
  74333. }
  74334. else {
  74335. normals.push(vn.x, vn.y, vn.z);
  74336. normals.push(vn.x, vn.y, vn.z);
  74337. normals.push(vn.x, vn.y, vn.z);
  74338. normals.push(vn.x, vn.y, vn.z);
  74339. indices.push(StartIndex);
  74340. indices.push(StartIndex + 2);
  74341. indices.push(StartIndex + 1);
  74342. indices.push(StartIndex + 1);
  74343. indices.push(StartIndex + 2);
  74344. indices.push(StartIndex + 3);
  74345. }
  74346. StartIndex += 4;
  74347. }
  74348. ;
  74349. };
  74350. return PolygonMeshBuilder;
  74351. }());
  74352. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  74353. })(BABYLON || (BABYLON = {}));
  74354. //# sourceMappingURL=babylon.polygonMesh.js.map
  74355. var BABYLON;
  74356. (function (BABYLON) {
  74357. // Unique ID when we import meshes from Babylon to CSG
  74358. var currentCSGMeshId = 0;
  74359. // # class Vertex
  74360. // Represents a vertex of a polygon. Use your own vertex class instead of this
  74361. // one to provide additional features like texture coordinates and vertex
  74362. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  74363. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  74364. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  74365. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  74366. // is not used anywhere else.
  74367. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  74368. var Vertex = /** @class */ (function () {
  74369. function Vertex(pos, normal, uv) {
  74370. this.pos = pos;
  74371. this.normal = normal;
  74372. this.uv = uv;
  74373. }
  74374. Vertex.prototype.clone = function () {
  74375. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  74376. };
  74377. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  74378. // orientation of a polygon is flipped.
  74379. Vertex.prototype.flip = function () {
  74380. this.normal = this.normal.scale(-1);
  74381. };
  74382. // Create a new vertex between this vertex and `other` by linearly
  74383. // interpolating all properties using a parameter of `t`. Subclasses should
  74384. // override this to interpolate additional properties.
  74385. Vertex.prototype.interpolate = function (other, t) {
  74386. 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));
  74387. };
  74388. return Vertex;
  74389. }());
  74390. // # class Plane
  74391. // Represents a plane in 3D space.
  74392. var Plane = /** @class */ (function () {
  74393. function Plane(normal, w) {
  74394. this.normal = normal;
  74395. this.w = w;
  74396. }
  74397. Plane.FromPoints = function (a, b, c) {
  74398. var v0 = c.subtract(a);
  74399. var v1 = b.subtract(a);
  74400. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  74401. return null;
  74402. }
  74403. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  74404. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  74405. };
  74406. Plane.prototype.clone = function () {
  74407. return new Plane(this.normal.clone(), this.w);
  74408. };
  74409. Plane.prototype.flip = function () {
  74410. this.normal.scaleInPlace(-1);
  74411. this.w = -this.w;
  74412. };
  74413. // Split `polygon` by this plane if needed, then put the polygon or polygon
  74414. // fragments in the appropriate lists. Coplanar polygons go into either
  74415. // `coplanarFront` or `coplanarBack` depending on their orientation with
  74416. // respect to this plane. Polygons in front or in back of this plane go into
  74417. // either `front` or `back`.
  74418. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  74419. var COPLANAR = 0;
  74420. var FRONT = 1;
  74421. var BACK = 2;
  74422. var SPANNING = 3;
  74423. // Classify each point as well as the entire polygon into one of the above
  74424. // four classes.
  74425. var polygonType = 0;
  74426. var types = [];
  74427. var i;
  74428. var t;
  74429. for (i = 0; i < polygon.vertices.length; i++) {
  74430. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  74431. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  74432. polygonType |= type;
  74433. types.push(type);
  74434. }
  74435. // Put the polygon in the correct list, splitting it when necessary.
  74436. switch (polygonType) {
  74437. case COPLANAR:
  74438. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  74439. break;
  74440. case FRONT:
  74441. front.push(polygon);
  74442. break;
  74443. case BACK:
  74444. back.push(polygon);
  74445. break;
  74446. case SPANNING:
  74447. var f = [], b = [];
  74448. for (i = 0; i < polygon.vertices.length; i++) {
  74449. var j = (i + 1) % polygon.vertices.length;
  74450. var ti = types[i], tj = types[j];
  74451. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  74452. if (ti !== BACK)
  74453. f.push(vi);
  74454. if (ti !== FRONT)
  74455. b.push(ti !== BACK ? vi.clone() : vi);
  74456. if ((ti | tj) === SPANNING) {
  74457. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  74458. var v = vi.interpolate(vj, t);
  74459. f.push(v);
  74460. b.push(v.clone());
  74461. }
  74462. }
  74463. var poly;
  74464. if (f.length >= 3) {
  74465. poly = new Polygon(f, polygon.shared);
  74466. if (poly.plane)
  74467. front.push(poly);
  74468. }
  74469. if (b.length >= 3) {
  74470. poly = new Polygon(b, polygon.shared);
  74471. if (poly.plane)
  74472. back.push(poly);
  74473. }
  74474. break;
  74475. }
  74476. };
  74477. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  74478. // point is on the plane.
  74479. Plane.EPSILON = 1e-5;
  74480. return Plane;
  74481. }());
  74482. // # class Polygon
  74483. // Represents a convex polygon. The vertices used to initialize a polygon must
  74484. // be coplanar and form a convex loop.
  74485. //
  74486. // Each convex polygon has a `shared` property, which is shared between all
  74487. // polygons that are clones of each other or were split from the same polygon.
  74488. // This can be used to define per-polygon properties (such as surface color).
  74489. var Polygon = /** @class */ (function () {
  74490. function Polygon(vertices, shared) {
  74491. this.vertices = vertices;
  74492. this.shared = shared;
  74493. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  74494. }
  74495. Polygon.prototype.clone = function () {
  74496. var vertices = this.vertices.map(function (v) { return v.clone(); });
  74497. return new Polygon(vertices, this.shared);
  74498. };
  74499. Polygon.prototype.flip = function () {
  74500. this.vertices.reverse().map(function (v) { v.flip(); });
  74501. this.plane.flip();
  74502. };
  74503. return Polygon;
  74504. }());
  74505. // # class Node
  74506. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  74507. // by picking a polygon to split along. That polygon (and all other coplanar
  74508. // polygons) are added directly to that node and the other polygons are added to
  74509. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  74510. // no distinction between internal and leaf nodes.
  74511. var Node = /** @class */ (function () {
  74512. function Node(polygons) {
  74513. this.plane = null;
  74514. this.front = null;
  74515. this.back = null;
  74516. this.polygons = new Array();
  74517. if (polygons) {
  74518. this.build(polygons);
  74519. }
  74520. }
  74521. Node.prototype.clone = function () {
  74522. var node = new Node();
  74523. node.plane = this.plane && this.plane.clone();
  74524. node.front = this.front && this.front.clone();
  74525. node.back = this.back && this.back.clone();
  74526. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  74527. return node;
  74528. };
  74529. // Convert solid space to empty space and empty space to solid space.
  74530. Node.prototype.invert = function () {
  74531. for (var i = 0; i < this.polygons.length; i++) {
  74532. this.polygons[i].flip();
  74533. }
  74534. if (this.plane) {
  74535. this.plane.flip();
  74536. }
  74537. if (this.front) {
  74538. this.front.invert();
  74539. }
  74540. if (this.back) {
  74541. this.back.invert();
  74542. }
  74543. var temp = this.front;
  74544. this.front = this.back;
  74545. this.back = temp;
  74546. };
  74547. // Recursively remove all polygons in `polygons` that are inside this BSP
  74548. // tree.
  74549. Node.prototype.clipPolygons = function (polygons) {
  74550. if (!this.plane)
  74551. return polygons.slice();
  74552. var front = new Array(), back = new Array();
  74553. for (var i = 0; i < polygons.length; i++) {
  74554. this.plane.splitPolygon(polygons[i], front, back, front, back);
  74555. }
  74556. if (this.front) {
  74557. front = this.front.clipPolygons(front);
  74558. }
  74559. if (this.back) {
  74560. back = this.back.clipPolygons(back);
  74561. }
  74562. else {
  74563. back = [];
  74564. }
  74565. return front.concat(back);
  74566. };
  74567. // Remove all polygons in this BSP tree that are inside the other BSP tree
  74568. // `bsp`.
  74569. Node.prototype.clipTo = function (bsp) {
  74570. this.polygons = bsp.clipPolygons(this.polygons);
  74571. if (this.front)
  74572. this.front.clipTo(bsp);
  74573. if (this.back)
  74574. this.back.clipTo(bsp);
  74575. };
  74576. // Return a list of all polygons in this BSP tree.
  74577. Node.prototype.allPolygons = function () {
  74578. var polygons = this.polygons.slice();
  74579. if (this.front)
  74580. polygons = polygons.concat(this.front.allPolygons());
  74581. if (this.back)
  74582. polygons = polygons.concat(this.back.allPolygons());
  74583. return polygons;
  74584. };
  74585. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  74586. // new polygons are filtered down to the bottom of the tree and become new
  74587. // nodes there. Each set of polygons is partitioned using the first polygon
  74588. // (no heuristic is used to pick a good split).
  74589. Node.prototype.build = function (polygons) {
  74590. if (!polygons.length)
  74591. return;
  74592. if (!this.plane)
  74593. this.plane = polygons[0].plane.clone();
  74594. var front = new Array(), back = new Array();
  74595. for (var i = 0; i < polygons.length; i++) {
  74596. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  74597. }
  74598. if (front.length) {
  74599. if (!this.front)
  74600. this.front = new Node();
  74601. this.front.build(front);
  74602. }
  74603. if (back.length) {
  74604. if (!this.back)
  74605. this.back = new Node();
  74606. this.back.build(back);
  74607. }
  74608. };
  74609. return Node;
  74610. }());
  74611. var CSG = /** @class */ (function () {
  74612. function CSG() {
  74613. this.polygons = new Array();
  74614. }
  74615. // Convert BABYLON.Mesh to BABYLON.CSG
  74616. CSG.FromMesh = function (mesh) {
  74617. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  74618. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  74619. if (mesh instanceof BABYLON.Mesh) {
  74620. mesh.computeWorldMatrix(true);
  74621. matrix = mesh.getWorldMatrix();
  74622. meshPosition = mesh.position.clone();
  74623. meshRotation = mesh.rotation.clone();
  74624. if (mesh.rotationQuaternion) {
  74625. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  74626. }
  74627. meshScaling = mesh.scaling.clone();
  74628. }
  74629. else {
  74630. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  74631. }
  74632. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  74633. var subMeshes = mesh.subMeshes;
  74634. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  74635. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  74636. vertices = [];
  74637. for (var j = 0; j < 3; j++) {
  74638. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  74639. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  74640. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  74641. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  74642. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  74643. vertex = new Vertex(position, normal, uv);
  74644. vertices.push(vertex);
  74645. }
  74646. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  74647. // To handle the case of degenerated triangle
  74648. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  74649. if (polygon.plane)
  74650. polygons.push(polygon);
  74651. }
  74652. }
  74653. var csg = CSG.FromPolygons(polygons);
  74654. csg.matrix = matrix;
  74655. csg.position = meshPosition;
  74656. csg.rotation = meshRotation;
  74657. csg.scaling = meshScaling;
  74658. csg.rotationQuaternion = meshRotationQuaternion;
  74659. currentCSGMeshId++;
  74660. return csg;
  74661. };
  74662. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  74663. CSG.FromPolygons = function (polygons) {
  74664. var csg = new CSG();
  74665. csg.polygons = polygons;
  74666. return csg;
  74667. };
  74668. CSG.prototype.clone = function () {
  74669. var csg = new CSG();
  74670. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  74671. csg.copyTransformAttributes(this);
  74672. return csg;
  74673. };
  74674. CSG.prototype.union = function (csg) {
  74675. var a = new Node(this.clone().polygons);
  74676. var b = new Node(csg.clone().polygons);
  74677. a.clipTo(b);
  74678. b.clipTo(a);
  74679. b.invert();
  74680. b.clipTo(a);
  74681. b.invert();
  74682. a.build(b.allPolygons());
  74683. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74684. };
  74685. CSG.prototype.unionInPlace = function (csg) {
  74686. var a = new Node(this.polygons);
  74687. var b = new Node(csg.polygons);
  74688. a.clipTo(b);
  74689. b.clipTo(a);
  74690. b.invert();
  74691. b.clipTo(a);
  74692. b.invert();
  74693. a.build(b.allPolygons());
  74694. this.polygons = a.allPolygons();
  74695. };
  74696. CSG.prototype.subtract = function (csg) {
  74697. var a = new Node(this.clone().polygons);
  74698. var b = new Node(csg.clone().polygons);
  74699. a.invert();
  74700. a.clipTo(b);
  74701. b.clipTo(a);
  74702. b.invert();
  74703. b.clipTo(a);
  74704. b.invert();
  74705. a.build(b.allPolygons());
  74706. a.invert();
  74707. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74708. };
  74709. CSG.prototype.subtractInPlace = function (csg) {
  74710. var a = new Node(this.polygons);
  74711. var b = new Node(csg.polygons);
  74712. a.invert();
  74713. a.clipTo(b);
  74714. b.clipTo(a);
  74715. b.invert();
  74716. b.clipTo(a);
  74717. b.invert();
  74718. a.build(b.allPolygons());
  74719. a.invert();
  74720. this.polygons = a.allPolygons();
  74721. };
  74722. CSG.prototype.intersect = function (csg) {
  74723. var a = new Node(this.clone().polygons);
  74724. var b = new Node(csg.clone().polygons);
  74725. a.invert();
  74726. b.clipTo(a);
  74727. b.invert();
  74728. a.clipTo(b);
  74729. b.clipTo(a);
  74730. a.build(b.allPolygons());
  74731. a.invert();
  74732. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74733. };
  74734. CSG.prototype.intersectInPlace = function (csg) {
  74735. var a = new Node(this.polygons);
  74736. var b = new Node(csg.polygons);
  74737. a.invert();
  74738. b.clipTo(a);
  74739. b.invert();
  74740. a.clipTo(b);
  74741. b.clipTo(a);
  74742. a.build(b.allPolygons());
  74743. a.invert();
  74744. this.polygons = a.allPolygons();
  74745. };
  74746. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  74747. // not modified.
  74748. CSG.prototype.inverse = function () {
  74749. var csg = this.clone();
  74750. csg.inverseInPlace();
  74751. return csg;
  74752. };
  74753. CSG.prototype.inverseInPlace = function () {
  74754. this.polygons.map(function (p) { p.flip(); });
  74755. };
  74756. // This is used to keep meshes transformations so they can be restored
  74757. // when we build back a Babylon Mesh
  74758. // NB : All CSG operations are performed in world coordinates
  74759. CSG.prototype.copyTransformAttributes = function (csg) {
  74760. this.matrix = csg.matrix;
  74761. this.position = csg.position;
  74762. this.rotation = csg.rotation;
  74763. this.scaling = csg.scaling;
  74764. this.rotationQuaternion = csg.rotationQuaternion;
  74765. return this;
  74766. };
  74767. // Build Raw mesh from CSG
  74768. // Coordinates here are in world space
  74769. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  74770. var matrix = this.matrix.clone();
  74771. matrix.invert();
  74772. 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;
  74773. if (keepSubMeshes) {
  74774. // Sort Polygons, since subMeshes are indices range
  74775. polygons.sort(function (a, b) {
  74776. if (a.shared.meshId === b.shared.meshId) {
  74777. return a.shared.subMeshId - b.shared.subMeshId;
  74778. }
  74779. else {
  74780. return a.shared.meshId - b.shared.meshId;
  74781. }
  74782. });
  74783. }
  74784. for (var i = 0, il = polygons.length; i < il; i++) {
  74785. polygon = polygons[i];
  74786. // Building SubMeshes
  74787. if (!subMesh_dict[polygon.shared.meshId]) {
  74788. subMesh_dict[polygon.shared.meshId] = {};
  74789. }
  74790. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  74791. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  74792. indexStart: +Infinity,
  74793. indexEnd: -Infinity,
  74794. materialIndex: polygon.shared.materialIndex
  74795. };
  74796. }
  74797. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  74798. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  74799. polygonIndices[0] = 0;
  74800. polygonIndices[1] = j - 1;
  74801. polygonIndices[2] = j;
  74802. for (var k = 0; k < 3; k++) {
  74803. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  74804. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  74805. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  74806. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  74807. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  74808. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  74809. // Check if 2 points can be merged
  74810. if (!(typeof vertex_idx !== 'undefined' &&
  74811. normals[vertex_idx * 3] === localNormal.x &&
  74812. normals[vertex_idx * 3 + 1] === localNormal.y &&
  74813. normals[vertex_idx * 3 + 2] === localNormal.z &&
  74814. uvs[vertex_idx * 2] === uv.x &&
  74815. uvs[vertex_idx * 2 + 1] === uv.y)) {
  74816. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  74817. uvs.push(uv.x, uv.y);
  74818. normals.push(normal.x, normal.y, normal.z);
  74819. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  74820. }
  74821. indices.push(vertex_idx);
  74822. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  74823. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  74824. currentIndex++;
  74825. }
  74826. }
  74827. }
  74828. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  74829. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  74830. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  74831. mesh.setIndices(indices, null);
  74832. if (keepSubMeshes) {
  74833. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  74834. var materialIndexOffset = 0, materialMaxIndex;
  74835. mesh.subMeshes = new Array();
  74836. for (var m in subMesh_dict) {
  74837. materialMaxIndex = -1;
  74838. for (var sm in subMesh_dict[m]) {
  74839. subMesh_obj = subMesh_dict[m][sm];
  74840. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  74841. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  74842. }
  74843. materialIndexOffset += ++materialMaxIndex;
  74844. }
  74845. }
  74846. return mesh;
  74847. };
  74848. // Build Mesh from CSG taking material and transforms into account
  74849. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  74850. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  74851. mesh.material = material;
  74852. mesh.position.copyFrom(this.position);
  74853. mesh.rotation.copyFrom(this.rotation);
  74854. if (this.rotationQuaternion) {
  74855. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  74856. }
  74857. mesh.scaling.copyFrom(this.scaling);
  74858. mesh.computeWorldMatrix(true);
  74859. return mesh;
  74860. };
  74861. return CSG;
  74862. }());
  74863. BABYLON.CSG = CSG;
  74864. })(BABYLON || (BABYLON = {}));
  74865. //# sourceMappingURL=babylon.csg.js.map
  74866. var BABYLON;
  74867. (function (BABYLON) {
  74868. var LensFlare = /** @class */ (function () {
  74869. function LensFlare(size, position, color, imgUrl, system) {
  74870. this.size = size;
  74871. this.position = position;
  74872. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74873. this.color = color || new BABYLON.Color3(1, 1, 1);
  74874. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  74875. this._system = system;
  74876. system.lensFlares.push(this);
  74877. }
  74878. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  74879. return new LensFlare(size, position, color, imgUrl, system);
  74880. };
  74881. LensFlare.prototype.dispose = function () {
  74882. if (this.texture) {
  74883. this.texture.dispose();
  74884. }
  74885. // Remove from scene
  74886. var index = this._system.lensFlares.indexOf(this);
  74887. this._system.lensFlares.splice(index, 1);
  74888. };
  74889. ;
  74890. return LensFlare;
  74891. }());
  74892. BABYLON.LensFlare = LensFlare;
  74893. })(BABYLON || (BABYLON = {}));
  74894. //# sourceMappingURL=babylon.lensFlare.js.map
  74895. var BABYLON;
  74896. (function (BABYLON) {
  74897. var LensFlareSystem = /** @class */ (function () {
  74898. function LensFlareSystem(name, emitter, scene) {
  74899. this.name = name;
  74900. this.lensFlares = new Array();
  74901. this.borderLimit = 300;
  74902. this.viewportBorder = 0;
  74903. this.layerMask = 0x0FFFFFFF;
  74904. this._vertexBuffers = {};
  74905. this._isEnabled = true;
  74906. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74907. this._emitter = emitter;
  74908. this.id = name;
  74909. scene.lensFlareSystems.push(this);
  74910. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  74911. var engine = scene.getEngine();
  74912. // VBO
  74913. var vertices = [];
  74914. vertices.push(1, 1);
  74915. vertices.push(-1, 1);
  74916. vertices.push(-1, -1);
  74917. vertices.push(1, -1);
  74918. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74919. // Indices
  74920. var indices = [];
  74921. indices.push(0);
  74922. indices.push(1);
  74923. indices.push(2);
  74924. indices.push(0);
  74925. indices.push(2);
  74926. indices.push(3);
  74927. this._indexBuffer = engine.createIndexBuffer(indices);
  74928. // Effects
  74929. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  74930. }
  74931. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  74932. get: function () {
  74933. return this._isEnabled;
  74934. },
  74935. set: function (value) {
  74936. this._isEnabled = value;
  74937. },
  74938. enumerable: true,
  74939. configurable: true
  74940. });
  74941. LensFlareSystem.prototype.getScene = function () {
  74942. return this._scene;
  74943. };
  74944. LensFlareSystem.prototype.getEmitter = function () {
  74945. return this._emitter;
  74946. };
  74947. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  74948. this._emitter = newEmitter;
  74949. };
  74950. LensFlareSystem.prototype.getEmitterPosition = function () {
  74951. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  74952. };
  74953. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  74954. var position = this.getEmitterPosition();
  74955. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  74956. this._positionX = position.x;
  74957. this._positionY = position.y;
  74958. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  74959. if (this.viewportBorder > 0) {
  74960. globalViewport.x -= this.viewportBorder;
  74961. globalViewport.y -= this.viewportBorder;
  74962. globalViewport.width += this.viewportBorder * 2;
  74963. globalViewport.height += this.viewportBorder * 2;
  74964. position.x += this.viewportBorder;
  74965. position.y += this.viewportBorder;
  74966. this._positionX += this.viewportBorder;
  74967. this._positionY += this.viewportBorder;
  74968. }
  74969. if (position.z > 0) {
  74970. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  74971. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  74972. return true;
  74973. }
  74974. return true;
  74975. }
  74976. return false;
  74977. };
  74978. LensFlareSystem.prototype._isVisible = function () {
  74979. if (!this._isEnabled || !this._scene.activeCamera) {
  74980. return false;
  74981. }
  74982. var emitterPosition = this.getEmitterPosition();
  74983. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  74984. var distance = direction.length();
  74985. direction.normalize();
  74986. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  74987. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  74988. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  74989. };
  74990. LensFlareSystem.prototype.render = function () {
  74991. if (!this._effect.isReady() || !this._scene.activeCamera)
  74992. return false;
  74993. var engine = this._scene.getEngine();
  74994. var viewport = this._scene.activeCamera.viewport;
  74995. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  74996. // Position
  74997. if (!this.computeEffectivePosition(globalViewport)) {
  74998. return false;
  74999. }
  75000. // Visibility
  75001. if (!this._isVisible()) {
  75002. return false;
  75003. }
  75004. // Intensity
  75005. var awayX;
  75006. var awayY;
  75007. if (this._positionX < this.borderLimit + globalViewport.x) {
  75008. awayX = this.borderLimit + globalViewport.x - this._positionX;
  75009. }
  75010. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  75011. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  75012. }
  75013. else {
  75014. awayX = 0;
  75015. }
  75016. if (this._positionY < this.borderLimit + globalViewport.y) {
  75017. awayY = this.borderLimit + globalViewport.y - this._positionY;
  75018. }
  75019. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  75020. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  75021. }
  75022. else {
  75023. awayY = 0;
  75024. }
  75025. var away = (awayX > awayY) ? awayX : awayY;
  75026. away -= this.viewportBorder;
  75027. if (away > this.borderLimit) {
  75028. away = this.borderLimit;
  75029. }
  75030. var intensity = 1.0 - (away / this.borderLimit);
  75031. if (intensity < 0) {
  75032. return false;
  75033. }
  75034. if (intensity > 1.0) {
  75035. intensity = 1.0;
  75036. }
  75037. if (this.viewportBorder > 0) {
  75038. globalViewport.x += this.viewportBorder;
  75039. globalViewport.y += this.viewportBorder;
  75040. globalViewport.width -= this.viewportBorder * 2;
  75041. globalViewport.height -= this.viewportBorder * 2;
  75042. this._positionX -= this.viewportBorder;
  75043. this._positionY -= this.viewportBorder;
  75044. }
  75045. // Position
  75046. var centerX = globalViewport.x + globalViewport.width / 2;
  75047. var centerY = globalViewport.y + globalViewport.height / 2;
  75048. var distX = centerX - this._positionX;
  75049. var distY = centerY - this._positionY;
  75050. // Effects
  75051. engine.enableEffect(this._effect);
  75052. engine.setState(false);
  75053. engine.setDepthBuffer(false);
  75054. // VBOs
  75055. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  75056. // Flares
  75057. for (var index = 0; index < this.lensFlares.length; index++) {
  75058. var flare = this.lensFlares[index];
  75059. engine.setAlphaMode(flare.alphaMode);
  75060. var x = centerX - (distX * flare.position);
  75061. var y = centerY - (distY * flare.position);
  75062. var cw = flare.size;
  75063. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  75064. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  75065. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  75066. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  75067. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  75068. // Texture
  75069. this._effect.setTexture("textureSampler", flare.texture);
  75070. // Color
  75071. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  75072. // Draw order
  75073. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75074. }
  75075. engine.setDepthBuffer(true);
  75076. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75077. return true;
  75078. };
  75079. LensFlareSystem.prototype.dispose = function () {
  75080. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75081. if (vertexBuffer) {
  75082. vertexBuffer.dispose();
  75083. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75084. }
  75085. if (this._indexBuffer) {
  75086. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75087. this._indexBuffer = null;
  75088. }
  75089. while (this.lensFlares.length) {
  75090. this.lensFlares[0].dispose();
  75091. }
  75092. // Remove from scene
  75093. var index = this._scene.lensFlareSystems.indexOf(this);
  75094. this._scene.lensFlareSystems.splice(index, 1);
  75095. };
  75096. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  75097. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  75098. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  75099. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  75100. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  75101. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  75102. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  75103. var parsedFlare = parsedLensFlareSystem.flares[index];
  75104. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  75105. }
  75106. return lensFlareSystem;
  75107. };
  75108. LensFlareSystem.prototype.serialize = function () {
  75109. var serializationObject = {};
  75110. serializationObject.id = this.id;
  75111. serializationObject.name = this.name;
  75112. serializationObject.emitterId = this.getEmitter().id;
  75113. serializationObject.borderLimit = this.borderLimit;
  75114. serializationObject.flares = [];
  75115. for (var index = 0; index < this.lensFlares.length; index++) {
  75116. var flare = this.lensFlares[index];
  75117. serializationObject.flares.push({
  75118. size: flare.size,
  75119. position: flare.position,
  75120. color: flare.color.asArray(),
  75121. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  75122. });
  75123. }
  75124. return serializationObject;
  75125. };
  75126. return LensFlareSystem;
  75127. }());
  75128. BABYLON.LensFlareSystem = LensFlareSystem;
  75129. })(BABYLON || (BABYLON = {}));
  75130. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  75131. var BABYLON;
  75132. (function (BABYLON) {
  75133. /**
  75134. * This is a holder class for the physics joint created by the physics plugin.
  75135. * It holds a set of functions to control the underlying joint.
  75136. */
  75137. var PhysicsJoint = /** @class */ (function () {
  75138. function PhysicsJoint(type, jointData) {
  75139. this.type = type;
  75140. this.jointData = jointData;
  75141. jointData.nativeParams = jointData.nativeParams || {};
  75142. }
  75143. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  75144. get: function () {
  75145. return this._physicsJoint;
  75146. },
  75147. set: function (newJoint) {
  75148. if (this._physicsJoint) {
  75149. //remove from the wolrd
  75150. }
  75151. this._physicsJoint = newJoint;
  75152. },
  75153. enumerable: true,
  75154. configurable: true
  75155. });
  75156. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  75157. set: function (physicsPlugin) {
  75158. this._physicsPlugin = physicsPlugin;
  75159. },
  75160. enumerable: true,
  75161. configurable: true
  75162. });
  75163. /**
  75164. * Execute a function that is physics-plugin specific.
  75165. * @param {Function} func the function that will be executed.
  75166. * It accepts two parameters: the physics world and the physics joint.
  75167. */
  75168. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  75169. func(this._physicsPlugin.world, this._physicsJoint);
  75170. };
  75171. //TODO check if the native joints are the same
  75172. //Joint Types
  75173. PhysicsJoint.DistanceJoint = 0;
  75174. PhysicsJoint.HingeJoint = 1;
  75175. PhysicsJoint.BallAndSocketJoint = 2;
  75176. PhysicsJoint.WheelJoint = 3;
  75177. PhysicsJoint.SliderJoint = 4;
  75178. //OIMO
  75179. PhysicsJoint.PrismaticJoint = 5;
  75180. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  75181. PhysicsJoint.UniversalJoint = 6;
  75182. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  75183. //Cannon
  75184. //Similar to a Ball-Joint. Different in params
  75185. PhysicsJoint.PointToPointJoint = 8;
  75186. //Cannon only at the moment
  75187. PhysicsJoint.SpringJoint = 9;
  75188. PhysicsJoint.LockJoint = 10;
  75189. return PhysicsJoint;
  75190. }());
  75191. BABYLON.PhysicsJoint = PhysicsJoint;
  75192. /**
  75193. * A class representing a physics distance joint.
  75194. */
  75195. var DistanceJoint = /** @class */ (function (_super) {
  75196. __extends(DistanceJoint, _super);
  75197. function DistanceJoint(jointData) {
  75198. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  75199. }
  75200. /**
  75201. * Update the predefined distance.
  75202. */
  75203. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  75204. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  75205. };
  75206. return DistanceJoint;
  75207. }(PhysicsJoint));
  75208. BABYLON.DistanceJoint = DistanceJoint;
  75209. var MotorEnabledJoint = /** @class */ (function (_super) {
  75210. __extends(MotorEnabledJoint, _super);
  75211. function MotorEnabledJoint(type, jointData) {
  75212. return _super.call(this, type, jointData) || this;
  75213. }
  75214. /**
  75215. * Set the motor values.
  75216. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75217. * @param {number} force the force to apply
  75218. * @param {number} maxForce max force for this motor.
  75219. */
  75220. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  75221. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75222. };
  75223. /**
  75224. * Set the motor's limits.
  75225. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75226. */
  75227. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75228. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75229. };
  75230. return MotorEnabledJoint;
  75231. }(PhysicsJoint));
  75232. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  75233. /**
  75234. * This class represents a single hinge physics joint
  75235. */
  75236. var HingeJoint = /** @class */ (function (_super) {
  75237. __extends(HingeJoint, _super);
  75238. function HingeJoint(jointData) {
  75239. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  75240. }
  75241. /**
  75242. * Set the motor values.
  75243. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75244. * @param {number} force the force to apply
  75245. * @param {number} maxForce max force for this motor.
  75246. */
  75247. HingeJoint.prototype.setMotor = function (force, maxForce) {
  75248. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  75249. };
  75250. /**
  75251. * Set the motor's limits.
  75252. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75253. */
  75254. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  75255. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  75256. };
  75257. return HingeJoint;
  75258. }(MotorEnabledJoint));
  75259. BABYLON.HingeJoint = HingeJoint;
  75260. /**
  75261. * This class represents a dual hinge physics joint (same as wheel joint)
  75262. */
  75263. var Hinge2Joint = /** @class */ (function (_super) {
  75264. __extends(Hinge2Joint, _super);
  75265. function Hinge2Joint(jointData) {
  75266. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  75267. }
  75268. /**
  75269. * Set the motor values.
  75270. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75271. * @param {number} force the force to apply
  75272. * @param {number} maxForce max force for this motor.
  75273. * @param {motorIndex} the motor's index, 0 or 1.
  75274. */
  75275. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  75276. if (motorIndex === void 0) { motorIndex = 0; }
  75277. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  75278. };
  75279. /**
  75280. * Set the motor limits.
  75281. * Attention, this function is plugin specific. Engines won't react 100% the same.
  75282. * @param {number} upperLimit the upper limit
  75283. * @param {number} lowerLimit lower limit
  75284. * @param {motorIndex} the motor's index, 0 or 1.
  75285. */
  75286. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  75287. if (motorIndex === void 0) { motorIndex = 0; }
  75288. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  75289. };
  75290. return Hinge2Joint;
  75291. }(MotorEnabledJoint));
  75292. BABYLON.Hinge2Joint = Hinge2Joint;
  75293. })(BABYLON || (BABYLON = {}));
  75294. //# sourceMappingURL=babylon.physicsJoint.js.map
  75295. var BABYLON;
  75296. (function (BABYLON) {
  75297. var PhysicsImpostor = /** @class */ (function () {
  75298. function PhysicsImpostor(object, type, _options, _scene) {
  75299. if (_options === void 0) { _options = { mass: 0 }; }
  75300. var _this = this;
  75301. this.object = object;
  75302. this.type = type;
  75303. this._options = _options;
  75304. this._scene = _scene;
  75305. this._bodyUpdateRequired = false;
  75306. this._onBeforePhysicsStepCallbacks = new Array();
  75307. this._onAfterPhysicsStepCallbacks = new Array();
  75308. this._onPhysicsCollideCallbacks = [];
  75309. this._deltaPosition = BABYLON.Vector3.Zero();
  75310. this._isDisposed = false;
  75311. //temp variables for parent rotation calculations
  75312. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  75313. this._tmpQuat = new BABYLON.Quaternion();
  75314. this._tmpQuat2 = new BABYLON.Quaternion();
  75315. /**
  75316. * this function is executed by the physics engine.
  75317. */
  75318. this.beforeStep = function () {
  75319. if (!_this._physicsEngine) {
  75320. return;
  75321. }
  75322. _this.object.translate(_this._deltaPosition, -1);
  75323. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  75324. _this.object.computeWorldMatrix(false);
  75325. if (_this.object.parent && _this.object.rotationQuaternion) {
  75326. _this.getParentsRotation();
  75327. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  75328. }
  75329. else {
  75330. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  75331. }
  75332. if (!_this._options.disableBidirectionalTransformation) {
  75333. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  75334. }
  75335. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  75336. func(_this);
  75337. });
  75338. };
  75339. /**
  75340. * this function is executed by the physics engine.
  75341. */
  75342. this.afterStep = function () {
  75343. if (!_this._physicsEngine) {
  75344. return;
  75345. }
  75346. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  75347. func(_this);
  75348. });
  75349. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  75350. // object has now its world rotation. needs to be converted to local.
  75351. if (_this.object.parent && _this.object.rotationQuaternion) {
  75352. _this.getParentsRotation();
  75353. _this._tmpQuat.conjugateInPlace();
  75354. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  75355. }
  75356. // take the position set and make it the absolute position of this object.
  75357. _this.object.setAbsolutePosition(_this.object.position);
  75358. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  75359. _this.object.translate(_this._deltaPosition, 1);
  75360. };
  75361. /**
  75362. * Legacy collision detection event support
  75363. */
  75364. this.onCollideEvent = null;
  75365. //event and body object due to cannon's event-based architecture.
  75366. this.onCollide = function (e) {
  75367. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  75368. return;
  75369. }
  75370. if (!_this._physicsEngine) {
  75371. return;
  75372. }
  75373. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  75374. if (otherImpostor) {
  75375. // Legacy collision detection event support
  75376. if (_this.onCollideEvent) {
  75377. _this.onCollideEvent(_this, otherImpostor);
  75378. }
  75379. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  75380. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  75381. }).forEach(function (obj) {
  75382. obj.callback(_this, otherImpostor);
  75383. });
  75384. }
  75385. };
  75386. //sanity check!
  75387. if (!this.object) {
  75388. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  75389. return;
  75390. }
  75391. //legacy support for old syntax.
  75392. if (!this._scene && object.getScene) {
  75393. this._scene = object.getScene();
  75394. }
  75395. if (!this._scene) {
  75396. return;
  75397. }
  75398. this._physicsEngine = this._scene.getPhysicsEngine();
  75399. if (!this._physicsEngine) {
  75400. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  75401. }
  75402. else {
  75403. //set the object's quaternion, if not set
  75404. if (!this.object.rotationQuaternion) {
  75405. if (this.object.rotation) {
  75406. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  75407. }
  75408. else {
  75409. this.object.rotationQuaternion = new BABYLON.Quaternion();
  75410. }
  75411. }
  75412. //default options params
  75413. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  75414. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  75415. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  75416. this._joints = [];
  75417. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  75418. if (!this.object.parent || this._options.ignoreParent) {
  75419. this._init();
  75420. }
  75421. else if (this.object.parent.physicsImpostor) {
  75422. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  75423. }
  75424. }
  75425. }
  75426. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  75427. get: function () {
  75428. return this._isDisposed;
  75429. },
  75430. enumerable: true,
  75431. configurable: true
  75432. });
  75433. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  75434. get: function () {
  75435. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  75436. },
  75437. set: function (value) {
  75438. this.setMass(value);
  75439. },
  75440. enumerable: true,
  75441. configurable: true
  75442. });
  75443. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  75444. get: function () {
  75445. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  75446. },
  75447. set: function (value) {
  75448. if (!this._physicsEngine) {
  75449. return;
  75450. }
  75451. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  75452. },
  75453. enumerable: true,
  75454. configurable: true
  75455. });
  75456. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  75457. get: function () {
  75458. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  75459. },
  75460. set: function (value) {
  75461. if (!this._physicsEngine) {
  75462. return;
  75463. }
  75464. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  75465. },
  75466. enumerable: true,
  75467. configurable: true
  75468. });
  75469. /**
  75470. * This function will completly initialize this impostor.
  75471. * It will create a new body - but only if this mesh has no parent.
  75472. * If it has, this impostor will not be used other than to define the impostor
  75473. * of the child mesh.
  75474. */
  75475. PhysicsImpostor.prototype._init = function () {
  75476. if (!this._physicsEngine) {
  75477. return;
  75478. }
  75479. this._physicsEngine.removeImpostor(this);
  75480. this.physicsBody = null;
  75481. this._parent = this._parent || this._getPhysicsParent();
  75482. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  75483. this._physicsEngine.addImpostor(this);
  75484. }
  75485. };
  75486. PhysicsImpostor.prototype._getPhysicsParent = function () {
  75487. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  75488. var parentMesh = this.object.parent;
  75489. return parentMesh.physicsImpostor;
  75490. }
  75491. return null;
  75492. };
  75493. /**
  75494. * Should a new body be generated.
  75495. */
  75496. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  75497. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  75498. };
  75499. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  75500. this.forceUpdate();
  75501. };
  75502. /**
  75503. * Force a regeneration of this or the parent's impostor's body.
  75504. * Use under cautious - This will remove all joints already implemented.
  75505. */
  75506. PhysicsImpostor.prototype.forceUpdate = function () {
  75507. this._init();
  75508. if (this.parent && !this._options.ignoreParent) {
  75509. this.parent.forceUpdate();
  75510. }
  75511. };
  75512. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  75513. /*public get mesh(): AbstractMesh {
  75514. return this._mesh;
  75515. }*/
  75516. /**
  75517. * Gets the body that holds this impostor. Either its own, or its parent.
  75518. */
  75519. get: function () {
  75520. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  75521. },
  75522. /**
  75523. * Set the physics body. Used mainly by the physics engine/plugin
  75524. */
  75525. set: function (physicsBody) {
  75526. if (this._physicsBody && this._physicsEngine) {
  75527. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  75528. }
  75529. this._physicsBody = physicsBody;
  75530. this.resetUpdateFlags();
  75531. },
  75532. enumerable: true,
  75533. configurable: true
  75534. });
  75535. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  75536. get: function () {
  75537. return !this._options.ignoreParent && this._parent ? this._parent : null;
  75538. },
  75539. set: function (value) {
  75540. this._parent = value;
  75541. },
  75542. enumerable: true,
  75543. configurable: true
  75544. });
  75545. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  75546. this._bodyUpdateRequired = false;
  75547. };
  75548. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  75549. if (this.object.getBoundingInfo) {
  75550. var q = this.object.rotationQuaternion;
  75551. //reset rotation
  75552. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  75553. //calculate the world matrix with no rotation
  75554. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75555. var boundingInfo = this.object.getBoundingInfo();
  75556. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  75557. //bring back the rotation
  75558. this.object.rotationQuaternion = q;
  75559. //calculate the world matrix with the new rotation
  75560. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75561. return size;
  75562. }
  75563. else {
  75564. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  75565. }
  75566. };
  75567. PhysicsImpostor.prototype.getObjectCenter = function () {
  75568. if (this.object.getBoundingInfo) {
  75569. var boundingInfo = this.object.getBoundingInfo();
  75570. return boundingInfo.boundingBox.centerWorld;
  75571. }
  75572. else {
  75573. return this.object.position;
  75574. }
  75575. };
  75576. /**
  75577. * Get a specific parametes from the options parameter.
  75578. */
  75579. PhysicsImpostor.prototype.getParam = function (paramName) {
  75580. return this._options[paramName];
  75581. };
  75582. /**
  75583. * Sets a specific parameter in the options given to the physics plugin
  75584. */
  75585. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  75586. this._options[paramName] = value;
  75587. this._bodyUpdateRequired = true;
  75588. };
  75589. /**
  75590. * Specifically change the body's mass option. Won't recreate the physics body object
  75591. */
  75592. PhysicsImpostor.prototype.setMass = function (mass) {
  75593. if (this.getParam("mass") !== mass) {
  75594. this.setParam("mass", mass);
  75595. }
  75596. if (this._physicsEngine) {
  75597. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  75598. }
  75599. };
  75600. PhysicsImpostor.prototype.getLinearVelocity = function () {
  75601. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  75602. };
  75603. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  75604. if (this._physicsEngine) {
  75605. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  75606. }
  75607. };
  75608. PhysicsImpostor.prototype.getAngularVelocity = function () {
  75609. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  75610. };
  75611. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  75612. if (this._physicsEngine) {
  75613. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  75614. }
  75615. };
  75616. /**
  75617. * Execute a function with the physics plugin native code.
  75618. * Provide a function the will have two variables - the world object and the physics body object.
  75619. */
  75620. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  75621. if (this._physicsEngine) {
  75622. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  75623. }
  75624. };
  75625. /**
  75626. * Register a function that will be executed before the physics world is stepping forward.
  75627. */
  75628. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  75629. this._onBeforePhysicsStepCallbacks.push(func);
  75630. };
  75631. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  75632. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  75633. if (index > -1) {
  75634. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  75635. }
  75636. else {
  75637. BABYLON.Tools.Warn("Function to remove was not found");
  75638. }
  75639. };
  75640. /**
  75641. * Register a function that will be executed after the physics step
  75642. */
  75643. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  75644. this._onAfterPhysicsStepCallbacks.push(func);
  75645. };
  75646. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  75647. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  75648. if (index > -1) {
  75649. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  75650. }
  75651. else {
  75652. BABYLON.Tools.Warn("Function to remove was not found");
  75653. }
  75654. };
  75655. /**
  75656. * register a function that will be executed when this impostor collides against a different body.
  75657. */
  75658. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  75659. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75660. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  75661. };
  75662. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  75663. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75664. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  75665. if (index > -1) {
  75666. this._onPhysicsCollideCallbacks.splice(index, 1);
  75667. }
  75668. else {
  75669. BABYLON.Tools.Warn("Function to remove was not found");
  75670. }
  75671. };
  75672. PhysicsImpostor.prototype.getParentsRotation = function () {
  75673. var parent = this.object.parent;
  75674. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  75675. while (parent) {
  75676. if (parent.rotationQuaternion) {
  75677. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  75678. }
  75679. else {
  75680. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  75681. }
  75682. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  75683. parent = parent.parent;
  75684. }
  75685. return this._tmpQuat;
  75686. };
  75687. /**
  75688. * Apply a force
  75689. */
  75690. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  75691. if (this._physicsEngine) {
  75692. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  75693. }
  75694. return this;
  75695. };
  75696. /**
  75697. * Apply an impulse
  75698. */
  75699. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  75700. if (this._physicsEngine) {
  75701. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  75702. }
  75703. return this;
  75704. };
  75705. /**
  75706. * A help function to create a joint.
  75707. */
  75708. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  75709. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  75710. this.addJoint(otherImpostor, joint);
  75711. return this;
  75712. };
  75713. /**
  75714. * Add a joint to this impostor with a different impostor.
  75715. */
  75716. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  75717. this._joints.push({
  75718. otherImpostor: otherImpostor,
  75719. joint: joint
  75720. });
  75721. if (this._physicsEngine) {
  75722. this._physicsEngine.addJoint(this, otherImpostor, joint);
  75723. }
  75724. return this;
  75725. };
  75726. /**
  75727. * Will keep this body still, in a sleep mode.
  75728. */
  75729. PhysicsImpostor.prototype.sleep = function () {
  75730. if (this._physicsEngine) {
  75731. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  75732. }
  75733. return this;
  75734. };
  75735. /**
  75736. * Wake the body up.
  75737. */
  75738. PhysicsImpostor.prototype.wakeUp = function () {
  75739. if (this._physicsEngine) {
  75740. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  75741. }
  75742. return this;
  75743. };
  75744. PhysicsImpostor.prototype.clone = function (newObject) {
  75745. if (!newObject)
  75746. return null;
  75747. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  75748. };
  75749. PhysicsImpostor.prototype.dispose = function () {
  75750. var _this = this;
  75751. //no dispose if no physics engine is available.
  75752. if (!this._physicsEngine) {
  75753. return;
  75754. }
  75755. this._joints.forEach(function (j) {
  75756. if (_this._physicsEngine) {
  75757. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  75758. }
  75759. });
  75760. //dispose the physics body
  75761. this._physicsEngine.removeImpostor(this);
  75762. if (this.parent) {
  75763. this.parent.forceUpdate();
  75764. }
  75765. else {
  75766. /*this._object.getChildMeshes().forEach(function(mesh) {
  75767. if (mesh.physicsImpostor) {
  75768. if (disposeChildren) {
  75769. mesh.physicsImpostor.dispose();
  75770. mesh.physicsImpostor = null;
  75771. }
  75772. }
  75773. })*/
  75774. }
  75775. this._isDisposed = true;
  75776. };
  75777. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  75778. this._deltaPosition.copyFrom(position);
  75779. };
  75780. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  75781. if (!this._deltaRotation) {
  75782. this._deltaRotation = new BABYLON.Quaternion();
  75783. }
  75784. this._deltaRotation.copyFrom(rotation);
  75785. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  75786. };
  75787. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  75788. if (this._physicsEngine) {
  75789. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  75790. }
  75791. return this;
  75792. };
  75793. PhysicsImpostor.prototype.getRadius = function () {
  75794. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  75795. };
  75796. /**
  75797. * Sync a bone with this impostor
  75798. * @param bone The bone to sync to the impostor.
  75799. * @param boneMesh The mesh that the bone is influencing.
  75800. * @param jointPivot The pivot of the joint / bone in local space.
  75801. * @param distToJoint Optional distance from the impostor to the joint.
  75802. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75803. */
  75804. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  75805. var tempVec = PhysicsImpostor._tmpVecs[0];
  75806. var mesh = this.object;
  75807. if (mesh.rotationQuaternion) {
  75808. if (adjustRotation) {
  75809. var tempQuat = PhysicsImpostor._tmpQuat;
  75810. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  75811. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  75812. }
  75813. else {
  75814. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  75815. }
  75816. }
  75817. tempVec.x = 0;
  75818. tempVec.y = 0;
  75819. tempVec.z = 0;
  75820. if (jointPivot) {
  75821. tempVec.x = jointPivot.x;
  75822. tempVec.y = jointPivot.y;
  75823. tempVec.z = jointPivot.z;
  75824. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  75825. if (distToJoint === undefined || distToJoint === null) {
  75826. distToJoint = jointPivot.length();
  75827. }
  75828. tempVec.x *= distToJoint;
  75829. tempVec.y *= distToJoint;
  75830. tempVec.z *= distToJoint;
  75831. }
  75832. if (bone.getParent()) {
  75833. tempVec.addInPlace(mesh.getAbsolutePosition());
  75834. bone.setAbsolutePosition(tempVec, boneMesh);
  75835. }
  75836. else {
  75837. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  75838. boneMesh.position.x -= tempVec.x;
  75839. boneMesh.position.y -= tempVec.y;
  75840. boneMesh.position.z -= tempVec.z;
  75841. }
  75842. };
  75843. /**
  75844. * Sync impostor to a bone
  75845. * @param bone The bone that the impostor will be synced to.
  75846. * @param boneMesh The mesh that the bone is influencing.
  75847. * @param jointPivot The pivot of the joint / bone in local space.
  75848. * @param distToJoint Optional distance from the impostor to the joint.
  75849. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75850. * @param boneAxis Optional vector3 axis the bone is aligned with
  75851. */
  75852. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  75853. var mesh = this.object;
  75854. if (mesh.rotationQuaternion) {
  75855. if (adjustRotation) {
  75856. var tempQuat = PhysicsImpostor._tmpQuat;
  75857. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  75858. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  75859. }
  75860. else {
  75861. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  75862. }
  75863. }
  75864. var pos = PhysicsImpostor._tmpVecs[0];
  75865. var boneDir = PhysicsImpostor._tmpVecs[1];
  75866. if (!boneAxis) {
  75867. boneAxis = PhysicsImpostor._tmpVecs[2];
  75868. boneAxis.x = 0;
  75869. boneAxis.y = 1;
  75870. boneAxis.z = 0;
  75871. }
  75872. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  75873. bone.getAbsolutePositionToRef(boneMesh, pos);
  75874. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  75875. distToJoint = jointPivot.length();
  75876. }
  75877. if (distToJoint !== undefined && distToJoint !== null) {
  75878. pos.x += boneDir.x * distToJoint;
  75879. pos.y += boneDir.y * distToJoint;
  75880. pos.z += boneDir.z * distToJoint;
  75881. }
  75882. mesh.setAbsolutePosition(pos);
  75883. };
  75884. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  75885. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  75886. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75887. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  75888. //Impostor types
  75889. PhysicsImpostor.NoImpostor = 0;
  75890. PhysicsImpostor.SphereImpostor = 1;
  75891. PhysicsImpostor.BoxImpostor = 2;
  75892. PhysicsImpostor.PlaneImpostor = 3;
  75893. PhysicsImpostor.MeshImpostor = 4;
  75894. PhysicsImpostor.CylinderImpostor = 7;
  75895. PhysicsImpostor.ParticleImpostor = 8;
  75896. PhysicsImpostor.HeightmapImpostor = 9;
  75897. return PhysicsImpostor;
  75898. }());
  75899. BABYLON.PhysicsImpostor = PhysicsImpostor;
  75900. })(BABYLON || (BABYLON = {}));
  75901. //# sourceMappingURL=babylon.physicsImpostor.js.map
  75902. var BABYLON;
  75903. (function (BABYLON) {
  75904. var PhysicsEngine = /** @class */ (function () {
  75905. function PhysicsEngine(gravity, _physicsPlugin) {
  75906. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  75907. this._physicsPlugin = _physicsPlugin;
  75908. //new methods and parameters
  75909. this._impostors = [];
  75910. this._joints = [];
  75911. if (!this._physicsPlugin.isSupported()) {
  75912. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  75913. + "Please make sure it is included.");
  75914. }
  75915. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  75916. this.setGravity(gravity);
  75917. this.setTimeStep();
  75918. }
  75919. PhysicsEngine.prototype.setGravity = function (gravity) {
  75920. this.gravity = gravity;
  75921. this._physicsPlugin.setGravity(this.gravity);
  75922. };
  75923. /**
  75924. * Set the time step of the physics engine.
  75925. * default is 1/60.
  75926. * To slow it down, enter 1/600 for example.
  75927. * To speed it up, 1/30
  75928. * @param {number} newTimeStep the new timestep to apply to this world.
  75929. */
  75930. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  75931. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  75932. this._physicsPlugin.setTimeStep(newTimeStep);
  75933. };
  75934. /**
  75935. * Get the time step of the physics engine.
  75936. */
  75937. PhysicsEngine.prototype.getTimeStep = function () {
  75938. return this._physicsPlugin.getTimeStep();
  75939. };
  75940. PhysicsEngine.prototype.dispose = function () {
  75941. this._impostors.forEach(function (impostor) {
  75942. impostor.dispose();
  75943. });
  75944. this._physicsPlugin.dispose();
  75945. };
  75946. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  75947. return this._physicsPlugin.name;
  75948. };
  75949. /**
  75950. * Adding a new impostor for the impostor tracking.
  75951. * This will be done by the impostor itself.
  75952. * @param {PhysicsImpostor} impostor the impostor to add
  75953. */
  75954. PhysicsEngine.prototype.addImpostor = function (impostor) {
  75955. impostor.uniqueId = this._impostors.push(impostor);
  75956. //if no parent, generate the body
  75957. if (!impostor.parent) {
  75958. this._physicsPlugin.generatePhysicsBody(impostor);
  75959. }
  75960. };
  75961. /**
  75962. * Remove an impostor from the engine.
  75963. * This impostor and its mesh will not longer be updated by the physics engine.
  75964. * @param {PhysicsImpostor} impostor the impostor to remove
  75965. */
  75966. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  75967. var index = this._impostors.indexOf(impostor);
  75968. if (index > -1) {
  75969. var removed = this._impostors.splice(index, 1);
  75970. //Is it needed?
  75971. if (removed.length) {
  75972. //this will also remove it from the world.
  75973. removed[0].physicsBody = null;
  75974. }
  75975. }
  75976. };
  75977. /**
  75978. * Add a joint to the physics engine
  75979. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  75980. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  75981. * @param {PhysicsJoint} the joint that will connect both impostors.
  75982. */
  75983. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  75984. var impostorJoint = {
  75985. mainImpostor: mainImpostor,
  75986. connectedImpostor: connectedImpostor,
  75987. joint: joint
  75988. };
  75989. joint.physicsPlugin = this._physicsPlugin;
  75990. this._joints.push(impostorJoint);
  75991. this._physicsPlugin.generateJoint(impostorJoint);
  75992. };
  75993. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  75994. var matchingJoints = this._joints.filter(function (impostorJoint) {
  75995. return (impostorJoint.connectedImpostor === connectedImpostor
  75996. && impostorJoint.joint === joint
  75997. && impostorJoint.mainImpostor === mainImpostor);
  75998. });
  75999. if (matchingJoints.length) {
  76000. this._physicsPlugin.removeJoint(matchingJoints[0]);
  76001. //TODO remove it from the list as well
  76002. }
  76003. };
  76004. /**
  76005. * Called by the scene. no need to call it.
  76006. */
  76007. PhysicsEngine.prototype._step = function (delta) {
  76008. var _this = this;
  76009. //check if any mesh has no body / requires an update
  76010. this._impostors.forEach(function (impostor) {
  76011. if (impostor.isBodyInitRequired()) {
  76012. _this._physicsPlugin.generatePhysicsBody(impostor);
  76013. }
  76014. });
  76015. if (delta > 0.1) {
  76016. delta = 0.1;
  76017. }
  76018. else if (delta <= 0) {
  76019. delta = 1.0 / 60.0;
  76020. }
  76021. this._physicsPlugin.executeStep(delta, this._impostors);
  76022. };
  76023. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  76024. return this._physicsPlugin;
  76025. };
  76026. PhysicsEngine.prototype.getImpostors = function () {
  76027. return this._impostors;
  76028. };
  76029. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  76030. for (var i = 0; i < this._impostors.length; ++i) {
  76031. if (this._impostors[i].object === object) {
  76032. return this._impostors[i];
  76033. }
  76034. }
  76035. return null;
  76036. };
  76037. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  76038. for (var i = 0; i < this._impostors.length; ++i) {
  76039. if (this._impostors[i].physicsBody === body) {
  76040. return this._impostors[i];
  76041. }
  76042. }
  76043. return null;
  76044. };
  76045. // Statics
  76046. PhysicsEngine.Epsilon = 0.001;
  76047. return PhysicsEngine;
  76048. }());
  76049. BABYLON.PhysicsEngine = PhysicsEngine;
  76050. })(BABYLON || (BABYLON = {}));
  76051. //# sourceMappingURL=babylon.physicsEngine.js.map
  76052. var BABYLON;
  76053. (function (BABYLON) {
  76054. var PhysicsHelper = /** @class */ (function () {
  76055. function PhysicsHelper(scene) {
  76056. this._scene = scene;
  76057. this._physicsEngine = this._scene.getPhysicsEngine();
  76058. if (!this._physicsEngine) {
  76059. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  76060. }
  76061. }
  76062. /**
  76063. * @param {Vector3} origin the origin of the explosion
  76064. * @param {number} radius the explosion radius
  76065. * @param {number} strength the explosion strength
  76066. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76067. */
  76068. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  76069. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76070. if (!this._physicsEngine) {
  76071. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  76072. return null;
  76073. }
  76074. var impostors = this._physicsEngine.getImpostors();
  76075. if (impostors.length === 0) {
  76076. return null;
  76077. }
  76078. var event = new PhysicsRadialExplosionEvent(this._scene);
  76079. impostors.forEach(function (impostor) {
  76080. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76081. if (!impostorForceAndContactPoint) {
  76082. return;
  76083. }
  76084. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76085. });
  76086. event.dispose(false);
  76087. return event;
  76088. };
  76089. /**
  76090. * @param {Vector3} origin the origin of the explosion
  76091. * @param {number} radius the explosion radius
  76092. * @param {number} strength the explosion strength
  76093. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76094. */
  76095. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  76096. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76097. if (!this._physicsEngine) {
  76098. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76099. return null;
  76100. }
  76101. var impostors = this._physicsEngine.getImpostors();
  76102. if (impostors.length === 0) {
  76103. return null;
  76104. }
  76105. var event = new PhysicsRadialExplosionEvent(this._scene);
  76106. impostors.forEach(function (impostor) {
  76107. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76108. if (!impostorForceAndContactPoint) {
  76109. return;
  76110. }
  76111. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76112. });
  76113. event.dispose(false);
  76114. return event;
  76115. };
  76116. /**
  76117. * @param {Vector3} origin the origin of the explosion
  76118. * @param {number} radius the explosion radius
  76119. * @param {number} strength the explosion strength
  76120. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76121. */
  76122. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  76123. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76124. if (!this._physicsEngine) {
  76125. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76126. return null;
  76127. }
  76128. var impostors = this._physicsEngine.getImpostors();
  76129. if (impostors.length === 0) {
  76130. return null;
  76131. }
  76132. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  76133. event.dispose(false);
  76134. return event;
  76135. };
  76136. /**
  76137. * @param {Vector3} origin the origin of the updraft
  76138. * @param {number} radius the radius of the updraft
  76139. * @param {number} strength the strength of the updraft
  76140. * @param {number} height the height of the updraft
  76141. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  76142. */
  76143. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  76144. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  76145. if (!this._physicsEngine) {
  76146. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76147. return null;
  76148. }
  76149. if (this._physicsEngine.getImpostors().length === 0) {
  76150. return null;
  76151. }
  76152. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  76153. event.dispose(false);
  76154. return event;
  76155. };
  76156. /**
  76157. * @param {Vector3} origin the of the vortex
  76158. * @param {number} radius the radius of the vortex
  76159. * @param {number} strength the strength of the vortex
  76160. * @param {number} height the height of the vortex
  76161. */
  76162. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  76163. if (!this._physicsEngine) {
  76164. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76165. return null;
  76166. }
  76167. if (this._physicsEngine.getImpostors().length === 0) {
  76168. return null;
  76169. }
  76170. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  76171. event.dispose(false);
  76172. return event;
  76173. };
  76174. return PhysicsHelper;
  76175. }());
  76176. BABYLON.PhysicsHelper = PhysicsHelper;
  76177. /***** Radial explosion *****/
  76178. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  76179. function PhysicsRadialExplosionEvent(scene) {
  76180. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  76181. this._rays = [];
  76182. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  76183. this._scene = scene;
  76184. }
  76185. /**
  76186. * Returns the data related to the radial explosion event (sphere & rays).
  76187. * @returns {PhysicsRadialExplosionEventData}
  76188. */
  76189. PhysicsRadialExplosionEvent.prototype.getData = function () {
  76190. this._dataFetched = true;
  76191. return {
  76192. sphere: this._sphere,
  76193. rays: this._rays,
  76194. };
  76195. };
  76196. /**
  76197. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  76198. * @param impostor
  76199. * @param {Vector3} origin the origin of the explosion
  76200. * @param {number} radius the explosion radius
  76201. * @param {number} strength the explosion strength
  76202. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  76203. * @returns {Nullable<PhysicsForceAndContactPoint>}
  76204. */
  76205. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  76206. if (impostor.mass === 0) {
  76207. return null;
  76208. }
  76209. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  76210. return null;
  76211. }
  76212. if (impostor.object.getClassName() !== 'Mesh') {
  76213. return null;
  76214. }
  76215. var impostorObject = impostor.object;
  76216. var impostorObjectCenter = impostor.getObjectCenter();
  76217. var direction = impostorObjectCenter.subtract(origin);
  76218. var ray = new BABYLON.Ray(origin, direction, radius);
  76219. this._rays.push(ray);
  76220. var hit = ray.intersectsMesh(impostorObject);
  76221. var contactPoint = hit.pickedPoint;
  76222. if (!contactPoint) {
  76223. return null;
  76224. }
  76225. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  76226. if (distanceFromOrigin > radius) {
  76227. return null;
  76228. }
  76229. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  76230. ? strength
  76231. : strength * (1 - (distanceFromOrigin / radius));
  76232. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76233. return { force: force, contactPoint: contactPoint };
  76234. };
  76235. /**
  76236. * Disposes the sphere.
  76237. * @param {bolean} force
  76238. */
  76239. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  76240. var _this = this;
  76241. if (force === void 0) { force = true; }
  76242. if (force) {
  76243. this._sphere.dispose();
  76244. }
  76245. else {
  76246. setTimeout(function () {
  76247. if (!_this._dataFetched) {
  76248. _this._sphere.dispose();
  76249. }
  76250. }, 0);
  76251. }
  76252. };
  76253. /*** Helpers ***/
  76254. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  76255. if (!this._sphere) {
  76256. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  76257. this._sphere.isVisible = false;
  76258. }
  76259. };
  76260. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  76261. var impostorObject = impostor.object;
  76262. this._prepareSphere();
  76263. this._sphere.position = origin;
  76264. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  76265. this._sphere._updateBoundingInfo();
  76266. this._sphere.computeWorldMatrix(true);
  76267. return this._sphere.intersectsMesh(impostorObject, true);
  76268. };
  76269. return PhysicsRadialExplosionEvent;
  76270. }());
  76271. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  76272. /***** Gravitational Field *****/
  76273. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  76274. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  76275. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76276. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76277. this._physicsHelper = physicsHelper;
  76278. this._scene = scene;
  76279. this._origin = origin;
  76280. this._radius = radius;
  76281. this._strength = strength;
  76282. this._falloff = falloff;
  76283. this._tickCallback = this._tick.bind(this);
  76284. }
  76285. /**
  76286. * Returns the data related to the gravitational field event (sphere).
  76287. * @returns {PhysicsGravitationalFieldEventData}
  76288. */
  76289. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  76290. this._dataFetched = true;
  76291. return {
  76292. sphere: this._sphere,
  76293. };
  76294. };
  76295. /**
  76296. * Enables the gravitational field.
  76297. */
  76298. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  76299. this._tickCallback.call(this);
  76300. this._scene.registerBeforeRender(this._tickCallback);
  76301. };
  76302. /**
  76303. * Disables the gravitational field.
  76304. */
  76305. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  76306. this._scene.unregisterBeforeRender(this._tickCallback);
  76307. };
  76308. /**
  76309. * Disposes the sphere.
  76310. * @param {bolean} force
  76311. */
  76312. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  76313. var _this = this;
  76314. if (force === void 0) { force = true; }
  76315. if (force) {
  76316. this._sphere.dispose();
  76317. }
  76318. else {
  76319. setTimeout(function () {
  76320. if (!_this._dataFetched) {
  76321. _this._sphere.dispose();
  76322. }
  76323. }, 0);
  76324. }
  76325. };
  76326. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  76327. // Since the params won't change, we fetch the event only once
  76328. if (this._sphere) {
  76329. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76330. }
  76331. else {
  76332. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  76333. if (radialExplosionEvent) {
  76334. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  76335. }
  76336. }
  76337. };
  76338. return PhysicsGravitationalFieldEvent;
  76339. }());
  76340. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  76341. /***** Updraft *****/
  76342. var PhysicsUpdraftEvent = /** @class */ (function () {
  76343. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  76344. this._scene = _scene;
  76345. this._origin = _origin;
  76346. this._radius = _radius;
  76347. this._strength = _strength;
  76348. this._height = _height;
  76349. this._updraftMode = _updraftMode;
  76350. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76351. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  76352. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76353. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76354. this._physicsEngine = this._scene.getPhysicsEngine();
  76355. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76356. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76357. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76358. this._originDirection = this._origin.subtract(this._originTop).normalize();
  76359. }
  76360. this._tickCallback = this._tick.bind(this);
  76361. }
  76362. /**
  76363. * Returns the data related to the updraft event (cylinder).
  76364. * @returns {PhysicsUpdraftEventData}
  76365. */
  76366. PhysicsUpdraftEvent.prototype.getData = function () {
  76367. this._dataFetched = true;
  76368. return {
  76369. cylinder: this._cylinder,
  76370. };
  76371. };
  76372. /**
  76373. * Enables the updraft.
  76374. */
  76375. PhysicsUpdraftEvent.prototype.enable = function () {
  76376. this._tickCallback.call(this);
  76377. this._scene.registerBeforeRender(this._tickCallback);
  76378. };
  76379. /**
  76380. * Disables the cortex.
  76381. */
  76382. PhysicsUpdraftEvent.prototype.disable = function () {
  76383. this._scene.unregisterBeforeRender(this._tickCallback);
  76384. };
  76385. /**
  76386. * Disposes the sphere.
  76387. * @param {bolean} force
  76388. */
  76389. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  76390. var _this = this;
  76391. if (force === void 0) { force = true; }
  76392. if (force) {
  76393. this._cylinder.dispose();
  76394. }
  76395. else {
  76396. setTimeout(function () {
  76397. if (!_this._dataFetched) {
  76398. _this._cylinder.dispose();
  76399. }
  76400. }, 0);
  76401. }
  76402. };
  76403. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76404. if (impostor.mass === 0) {
  76405. return null;
  76406. }
  76407. if (!this._intersectsWithCylinder(impostor)) {
  76408. return null;
  76409. }
  76410. var impostorObjectCenter = impostor.getObjectCenter();
  76411. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  76412. var direction = this._originDirection;
  76413. }
  76414. else {
  76415. var direction = impostorObjectCenter.subtract(this._originTop);
  76416. }
  76417. var multiplier = this._strength * -1;
  76418. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  76419. return { force: force, contactPoint: impostorObjectCenter };
  76420. };
  76421. PhysicsUpdraftEvent.prototype._tick = function () {
  76422. var _this = this;
  76423. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76424. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76425. if (!impostorForceAndContactPoint) {
  76426. return;
  76427. }
  76428. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76429. });
  76430. };
  76431. /*** Helpers ***/
  76432. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  76433. if (!this._cylinder) {
  76434. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  76435. height: this._height,
  76436. diameter: this._radius * 2,
  76437. }, this._scene);
  76438. this._cylinder.isVisible = false;
  76439. }
  76440. };
  76441. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  76442. var impostorObject = impostor.object;
  76443. this._prepareCylinder();
  76444. this._cylinder.position = this._cylinderPosition;
  76445. return this._cylinder.intersectsMesh(impostorObject, true);
  76446. };
  76447. return PhysicsUpdraftEvent;
  76448. }());
  76449. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  76450. /***** Vortex *****/
  76451. var PhysicsVortexEvent = /** @class */ (function () {
  76452. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  76453. this._scene = _scene;
  76454. this._origin = _origin;
  76455. this._radius = _radius;
  76456. this._strength = _strength;
  76457. this._height = _height;
  76458. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  76459. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  76460. this._updraftMultiplier = 0.02;
  76461. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  76462. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  76463. this._physicsEngine = this._scene.getPhysicsEngine();
  76464. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  76465. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  76466. this._tickCallback = this._tick.bind(this);
  76467. }
  76468. /**
  76469. * Returns the data related to the vortex event (cylinder).
  76470. * @returns {PhysicsVortexEventData}
  76471. */
  76472. PhysicsVortexEvent.prototype.getData = function () {
  76473. this._dataFetched = true;
  76474. return {
  76475. cylinder: this._cylinder,
  76476. };
  76477. };
  76478. /**
  76479. * Enables the vortex.
  76480. */
  76481. PhysicsVortexEvent.prototype.enable = function () {
  76482. this._tickCallback.call(this);
  76483. this._scene.registerBeforeRender(this._tickCallback);
  76484. };
  76485. /**
  76486. * Disables the cortex.
  76487. */
  76488. PhysicsVortexEvent.prototype.disable = function () {
  76489. this._scene.unregisterBeforeRender(this._tickCallback);
  76490. };
  76491. /**
  76492. * Disposes the sphere.
  76493. * @param {bolean} force
  76494. */
  76495. PhysicsVortexEvent.prototype.dispose = function (force) {
  76496. var _this = this;
  76497. if (force === void 0) { force = true; }
  76498. if (force) {
  76499. this._cylinder.dispose();
  76500. }
  76501. else {
  76502. setTimeout(function () {
  76503. if (!_this._dataFetched) {
  76504. _this._cylinder.dispose();
  76505. }
  76506. }, 0);
  76507. }
  76508. };
  76509. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  76510. if (impostor.mass === 0) {
  76511. return null;
  76512. }
  76513. if (!this._intersectsWithCylinder(impostor)) {
  76514. return null;
  76515. }
  76516. if (impostor.object.getClassName() !== 'Mesh') {
  76517. return null;
  76518. }
  76519. var impostorObject = impostor.object;
  76520. var impostorObjectCenter = impostor.getObjectCenter();
  76521. 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)
  76522. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  76523. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  76524. var hit = ray.intersectsMesh(impostorObject);
  76525. var contactPoint = hit.pickedPoint;
  76526. if (!contactPoint) {
  76527. return null;
  76528. }
  76529. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  76530. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  76531. var directionToOrigin = contactPoint.normalize();
  76532. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76533. directionToOrigin = directionToOrigin.negate();
  76534. }
  76535. // TODO: find a more physically based solution
  76536. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76537. var forceX = directionToOrigin.x * this._strength / 8;
  76538. var forceY = directionToOrigin.y * this._updraftMultiplier;
  76539. var forceZ = directionToOrigin.z * this._strength / 8;
  76540. }
  76541. else {
  76542. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  76543. var forceY = this._originTop.y * this._updraftMultiplier;
  76544. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  76545. }
  76546. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  76547. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  76548. return { force: force, contactPoint: impostorObjectCenter };
  76549. };
  76550. PhysicsVortexEvent.prototype._tick = function () {
  76551. var _this = this;
  76552. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76553. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76554. if (!impostorForceAndContactPoint) {
  76555. return;
  76556. }
  76557. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76558. });
  76559. };
  76560. /*** Helpers ***/
  76561. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  76562. if (!this._cylinder) {
  76563. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  76564. height: this._height,
  76565. diameter: this._radius * 2,
  76566. }, this._scene);
  76567. this._cylinder.isVisible = false;
  76568. }
  76569. };
  76570. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  76571. var impostorObject = impostor.object;
  76572. this._prepareCylinder();
  76573. this._cylinder.position = this._cylinderPosition;
  76574. return this._cylinder.intersectsMesh(impostorObject, true);
  76575. };
  76576. return PhysicsVortexEvent;
  76577. }());
  76578. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  76579. /***** Enums *****/
  76580. /**
  76581. * The strenght of the force in correspondence to the distance of the affected object
  76582. */
  76583. var PhysicsRadialImpulseFalloff;
  76584. (function (PhysicsRadialImpulseFalloff) {
  76585. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  76586. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  76587. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  76588. /**
  76589. * The strenght of the force in correspondence to the distance of the affected object
  76590. */
  76591. var PhysicsUpdraftMode;
  76592. (function (PhysicsUpdraftMode) {
  76593. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  76594. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  76595. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  76596. })(BABYLON || (BABYLON = {}));
  76597. //# sourceMappingURL=babylon.physicsHelper.js.map
  76598. var BABYLON;
  76599. (function (BABYLON) {
  76600. var CannonJSPlugin = /** @class */ (function () {
  76601. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  76602. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  76603. if (iterations === void 0) { iterations = 10; }
  76604. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  76605. this.name = "CannonJSPlugin";
  76606. this._physicsMaterials = new Array();
  76607. this._fixedTimeStep = 1 / 60;
  76608. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  76609. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  76610. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  76611. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  76612. this._tmpPosition = BABYLON.Vector3.Zero();
  76613. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  76614. this._tmpUnityRotation = new BABYLON.Quaternion();
  76615. if (!this.isSupported()) {
  76616. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  76617. return;
  76618. }
  76619. this._extendNamespace();
  76620. this.world = new this.BJSCANNON.World();
  76621. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  76622. this.world.solver.iterations = iterations;
  76623. }
  76624. CannonJSPlugin.prototype.setGravity = function (gravity) {
  76625. this.world.gravity.copy(gravity);
  76626. };
  76627. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  76628. this._fixedTimeStep = timeStep;
  76629. };
  76630. CannonJSPlugin.prototype.getTimeStep = function () {
  76631. return this._fixedTimeStep;
  76632. };
  76633. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  76634. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  76635. };
  76636. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76637. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76638. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76639. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  76640. };
  76641. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76642. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76643. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76644. impostor.physicsBody.applyForce(impulse, worldPoint);
  76645. };
  76646. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76647. //parent-child relationship. Does this impostor has a parent impostor?
  76648. if (impostor.parent) {
  76649. if (impostor.physicsBody) {
  76650. this.removePhysicsBody(impostor);
  76651. //TODO is that needed?
  76652. impostor.forceUpdate();
  76653. }
  76654. return;
  76655. }
  76656. //should a new body be created for this impostor?
  76657. if (impostor.isBodyInitRequired()) {
  76658. var shape = this._createShape(impostor);
  76659. //unregister events, if body is being changed
  76660. var oldBody = impostor.physicsBody;
  76661. if (oldBody) {
  76662. this.removePhysicsBody(impostor);
  76663. }
  76664. //create the body and material
  76665. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  76666. var bodyCreationObject = {
  76667. mass: impostor.getParam("mass"),
  76668. material: material
  76669. };
  76670. // A simple extend, in case native options were used.
  76671. var nativeOptions = impostor.getParam("nativeOptions");
  76672. for (var key in nativeOptions) {
  76673. if (nativeOptions.hasOwnProperty(key)) {
  76674. bodyCreationObject[key] = nativeOptions[key];
  76675. }
  76676. }
  76677. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  76678. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  76679. this.world.addEventListener("preStep", impostor.beforeStep);
  76680. this.world.addEventListener("postStep", impostor.afterStep);
  76681. impostor.physicsBody.addShape(shape);
  76682. this.world.add(impostor.physicsBody);
  76683. //try to keep the body moving in the right direction by taking old properties.
  76684. //Should be tested!
  76685. if (oldBody) {
  76686. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  76687. impostor.physicsBody[param].copy(oldBody[param]);
  76688. });
  76689. }
  76690. this._processChildMeshes(impostor);
  76691. }
  76692. //now update the body's transformation
  76693. this._updatePhysicsBodyTransformation(impostor);
  76694. };
  76695. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  76696. var _this = this;
  76697. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  76698. var currentRotation = mainImpostor.object.rotationQuaternion;
  76699. if (meshChildren.length) {
  76700. var processMesh = function (localPosition, mesh) {
  76701. if (!currentRotation || !mesh.rotationQuaternion) {
  76702. return;
  76703. }
  76704. var childImpostor = mesh.getPhysicsImpostor();
  76705. if (childImpostor) {
  76706. var parent = childImpostor.parent;
  76707. if (parent !== mainImpostor) {
  76708. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  76709. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  76710. if (childImpostor.physicsBody) {
  76711. _this.removePhysicsBody(childImpostor);
  76712. childImpostor.physicsBody = null;
  76713. }
  76714. childImpostor.parent = mainImpostor;
  76715. childImpostor.resetUpdateFlags();
  76716. 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));
  76717. //Add the mass of the children.
  76718. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  76719. }
  76720. }
  76721. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  76722. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  76723. };
  76724. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  76725. }
  76726. };
  76727. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  76728. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  76729. this.world.removeEventListener("preStep", impostor.beforeStep);
  76730. this.world.removeEventListener("postStep", impostor.afterStep);
  76731. this.world.remove(impostor.physicsBody);
  76732. };
  76733. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76734. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76735. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76736. if (!mainBody || !connectedBody) {
  76737. return;
  76738. }
  76739. var constraint;
  76740. var jointData = impostorJoint.joint.jointData;
  76741. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  76742. var constraintData = {
  76743. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  76744. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  76745. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  76746. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  76747. maxForce: jointData.nativeParams.maxForce,
  76748. collideConnected: !!jointData.collision
  76749. };
  76750. switch (impostorJoint.joint.type) {
  76751. case BABYLON.PhysicsJoint.HingeJoint:
  76752. case BABYLON.PhysicsJoint.Hinge2Joint:
  76753. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  76754. break;
  76755. case BABYLON.PhysicsJoint.DistanceJoint:
  76756. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  76757. break;
  76758. case BABYLON.PhysicsJoint.SpringJoint:
  76759. var springData = jointData;
  76760. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  76761. restLength: springData.length,
  76762. stiffness: springData.stiffness,
  76763. damping: springData.damping,
  76764. localAnchorA: constraintData.pivotA,
  76765. localAnchorB: constraintData.pivotB
  76766. });
  76767. break;
  76768. case BABYLON.PhysicsJoint.LockJoint:
  76769. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  76770. break;
  76771. case BABYLON.PhysicsJoint.PointToPointJoint:
  76772. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76773. default:
  76774. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  76775. break;
  76776. }
  76777. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  76778. constraint.collideConnected = !!jointData.collision;
  76779. impostorJoint.joint.physicsJoint = constraint;
  76780. //don't add spring as constraint, as it is not one.
  76781. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  76782. this.world.addConstraint(constraint);
  76783. }
  76784. else {
  76785. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  76786. constraint.applyForce();
  76787. });
  76788. }
  76789. };
  76790. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76791. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  76792. };
  76793. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  76794. var index;
  76795. var mat;
  76796. for (index = 0; index < this._physicsMaterials.length; index++) {
  76797. mat = this._physicsMaterials[index];
  76798. if (mat.friction === friction && mat.restitution === restitution) {
  76799. return mat;
  76800. }
  76801. }
  76802. var currentMat = new this.BJSCANNON.Material(name);
  76803. currentMat.friction = friction;
  76804. currentMat.restitution = restitution;
  76805. this._physicsMaterials.push(currentMat);
  76806. return currentMat;
  76807. };
  76808. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  76809. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  76810. };
  76811. CannonJSPlugin.prototype._createShape = function (impostor) {
  76812. var object = impostor.object;
  76813. var returnValue;
  76814. var extendSize = impostor.getObjectExtendSize();
  76815. switch (impostor.type) {
  76816. case BABYLON.PhysicsImpostor.SphereImpostor:
  76817. var radiusX = extendSize.x;
  76818. var radiusY = extendSize.y;
  76819. var radiusZ = extendSize.z;
  76820. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  76821. break;
  76822. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  76823. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76824. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  76825. break;
  76826. case BABYLON.PhysicsImpostor.BoxImpostor:
  76827. var box = extendSize.scale(0.5);
  76828. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  76829. break;
  76830. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76831. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  76832. returnValue = new this.BJSCANNON.Plane();
  76833. break;
  76834. case BABYLON.PhysicsImpostor.MeshImpostor:
  76835. // should transform the vertex data to world coordinates!!
  76836. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  76837. var rawFaces = object.getIndices ? object.getIndices() : [];
  76838. if (!rawVerts)
  76839. return;
  76840. // get only scale! so the object could transform correctly.
  76841. var oldPosition = object.position.clone();
  76842. var oldRotation = object.rotation && object.rotation.clone();
  76843. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  76844. object.position.copyFromFloats(0, 0, 0);
  76845. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76846. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76847. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76848. var transform = object.computeWorldMatrix(true);
  76849. // convert rawVerts to object space
  76850. var temp = new Array();
  76851. var index;
  76852. for (index = 0; index < rawVerts.length; index += 3) {
  76853. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  76854. }
  76855. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  76856. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  76857. //now set back the transformation!
  76858. object.position.copyFrom(oldPosition);
  76859. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  76860. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  76861. break;
  76862. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  76863. var oldPosition2 = object.position.clone();
  76864. var oldRotation2 = object.rotation && object.rotation.clone();
  76865. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  76866. object.position.copyFromFloats(0, 0, 0);
  76867. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76868. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76869. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76870. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  76871. returnValue = this._createHeightmap(object);
  76872. object.position.copyFrom(oldPosition2);
  76873. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  76874. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  76875. object.computeWorldMatrix(true);
  76876. break;
  76877. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76878. returnValue = new this.BJSCANNON.Particle();
  76879. break;
  76880. }
  76881. return returnValue;
  76882. };
  76883. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  76884. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76885. var transform = object.computeWorldMatrix(true);
  76886. // convert rawVerts to object space
  76887. var temp = new Array();
  76888. var index;
  76889. for (index = 0; index < pos.length; index += 3) {
  76890. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  76891. }
  76892. pos = temp;
  76893. var matrix = new Array();
  76894. //For now pointDepth will not be used and will be automatically calculated.
  76895. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  76896. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  76897. var boundingInfo = object.getBoundingInfo();
  76898. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  76899. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  76900. var elementSize = dim * 2 / arraySize;
  76901. for (var i = 0; i < pos.length; i = i + 3) {
  76902. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  76903. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  76904. var y = -pos[i + 2] + minY;
  76905. if (!matrix[x]) {
  76906. matrix[x] = [];
  76907. }
  76908. if (!matrix[x][z]) {
  76909. matrix[x][z] = y;
  76910. }
  76911. matrix[x][z] = Math.max(y, matrix[x][z]);
  76912. }
  76913. for (var x = 0; x <= arraySize; ++x) {
  76914. if (!matrix[x]) {
  76915. var loc = 1;
  76916. while (!matrix[(x + loc) % arraySize]) {
  76917. loc++;
  76918. }
  76919. matrix[x] = matrix[(x + loc) % arraySize].slice();
  76920. //console.log("missing x", x);
  76921. }
  76922. for (var z = 0; z <= arraySize; ++z) {
  76923. if (!matrix[x][z]) {
  76924. var loc = 1;
  76925. var newValue;
  76926. while (newValue === undefined) {
  76927. newValue = matrix[x][(z + loc++) % arraySize];
  76928. }
  76929. matrix[x][z] = newValue;
  76930. }
  76931. }
  76932. }
  76933. var shape = new this.BJSCANNON.Heightfield(matrix, {
  76934. elementSize: elementSize
  76935. });
  76936. //For future reference, needed for body transformation
  76937. shape.minY = minY;
  76938. return shape;
  76939. };
  76940. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  76941. var object = impostor.object;
  76942. //make sure it is updated...
  76943. object.computeWorldMatrix && object.computeWorldMatrix(true);
  76944. // The delta between the mesh position and the mesh bounding box center
  76945. var bInfo = object.getBoundingInfo();
  76946. if (!bInfo)
  76947. return;
  76948. var center = impostor.getObjectCenter();
  76949. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  76950. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  76951. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  76952. this._tmpPosition.copyFrom(center);
  76953. var quaternion = object.rotationQuaternion;
  76954. if (!quaternion) {
  76955. return;
  76956. }
  76957. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  76958. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  76959. //-90 DEG in X, precalculated
  76960. quaternion = quaternion.multiply(this._minus90X);
  76961. //Invert! (Precalculated, 90 deg in X)
  76962. //No need to clone. this will never change.
  76963. impostor.setDeltaRotation(this._plus90X);
  76964. }
  76965. //If it is a heightfield, if should be centered.
  76966. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  76967. var mesh = object;
  76968. var boundingInfo = mesh.getBoundingInfo();
  76969. //calculate the correct body position:
  76970. var rotationQuaternion = mesh.rotationQuaternion;
  76971. mesh.rotationQuaternion = this._tmpUnityRotation;
  76972. mesh.computeWorldMatrix(true);
  76973. //get original center with no rotation
  76974. var c = center.clone();
  76975. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  76976. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  76977. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  76978. mesh.setPreTransformMatrix(p);
  76979. mesh.computeWorldMatrix(true);
  76980. //calculate the translation
  76981. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  76982. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  76983. //add it inverted to the delta
  76984. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  76985. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  76986. //rotation is back
  76987. mesh.rotationQuaternion = rotationQuaternion;
  76988. mesh.setPreTransformMatrix(oldPivot);
  76989. mesh.computeWorldMatrix(true);
  76990. }
  76991. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  76992. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  76993. //this._tmpPosition.copyFrom(object.position);
  76994. }
  76995. impostor.setDeltaPosition(this._tmpDeltaPosition);
  76996. //Now update the impostor object
  76997. impostor.physicsBody.position.copy(this._tmpPosition);
  76998. impostor.physicsBody.quaternion.copy(quaternion);
  76999. };
  77000. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77001. impostor.object.position.copyFrom(impostor.physicsBody.position);
  77002. if (impostor.object.rotationQuaternion) {
  77003. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  77004. }
  77005. };
  77006. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77007. impostor.physicsBody.position.copy(newPosition);
  77008. impostor.physicsBody.quaternion.copy(newRotation);
  77009. };
  77010. CannonJSPlugin.prototype.isSupported = function () {
  77011. return this.BJSCANNON !== undefined;
  77012. };
  77013. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77014. impostor.physicsBody.velocity.copy(velocity);
  77015. };
  77016. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77017. impostor.physicsBody.angularVelocity.copy(velocity);
  77018. };
  77019. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77020. var v = impostor.physicsBody.velocity;
  77021. if (!v) {
  77022. return null;
  77023. }
  77024. return new BABYLON.Vector3(v.x, v.y, v.z);
  77025. };
  77026. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77027. var v = impostor.physicsBody.angularVelocity;
  77028. if (!v) {
  77029. return null;
  77030. }
  77031. return new BABYLON.Vector3(v.x, v.y, v.z);
  77032. };
  77033. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77034. impostor.physicsBody.mass = mass;
  77035. impostor.physicsBody.updateMassProperties();
  77036. };
  77037. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  77038. return impostor.physicsBody.mass;
  77039. };
  77040. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  77041. return impostor.physicsBody.material.friction;
  77042. };
  77043. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77044. impostor.physicsBody.material.friction = friction;
  77045. };
  77046. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77047. return impostor.physicsBody.material.restitution;
  77048. };
  77049. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77050. impostor.physicsBody.material.restitution = restitution;
  77051. };
  77052. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  77053. impostor.physicsBody.sleep();
  77054. };
  77055. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  77056. impostor.physicsBody.wakeUp();
  77057. };
  77058. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77059. joint.physicsJoint.distance = maxDistance;
  77060. };
  77061. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77062. // if (!motorIndex) {
  77063. // joint.physicsJoint.enableMotor();
  77064. // }
  77065. // }
  77066. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77067. // if (!motorIndex) {
  77068. // joint.physicsJoint.disableMotor();
  77069. // }
  77070. // }
  77071. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77072. if (!motorIndex) {
  77073. joint.physicsJoint.enableMotor();
  77074. joint.physicsJoint.setMotorSpeed(speed);
  77075. if (maxForce) {
  77076. this.setLimit(joint, maxForce);
  77077. }
  77078. }
  77079. };
  77080. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  77081. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  77082. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  77083. };
  77084. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77085. var body = impostor.physicsBody;
  77086. mesh.position.x = body.position.x;
  77087. mesh.position.y = body.position.y;
  77088. mesh.position.z = body.position.z;
  77089. if (mesh.rotationQuaternion) {
  77090. mesh.rotationQuaternion.x = body.quaternion.x;
  77091. mesh.rotationQuaternion.y = body.quaternion.y;
  77092. mesh.rotationQuaternion.z = body.quaternion.z;
  77093. mesh.rotationQuaternion.w = body.quaternion.w;
  77094. }
  77095. };
  77096. CannonJSPlugin.prototype.getRadius = function (impostor) {
  77097. var shape = impostor.physicsBody.shapes[0];
  77098. return shape.boundingSphereRadius;
  77099. };
  77100. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77101. var shape = impostor.physicsBody.shapes[0];
  77102. result.x = shape.halfExtents.x * 2;
  77103. result.y = shape.halfExtents.y * 2;
  77104. result.z = shape.halfExtents.z * 2;
  77105. };
  77106. CannonJSPlugin.prototype.dispose = function () {
  77107. };
  77108. CannonJSPlugin.prototype._extendNamespace = function () {
  77109. //this will force cannon to execute at least one step when using interpolation
  77110. var step_tmp1 = new this.BJSCANNON.Vec3();
  77111. var Engine = this.BJSCANNON;
  77112. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  77113. maxSubSteps = maxSubSteps || 10;
  77114. timeSinceLastCalled = timeSinceLastCalled || 0;
  77115. if (timeSinceLastCalled === 0) {
  77116. this.internalStep(dt);
  77117. this.time += dt;
  77118. }
  77119. else {
  77120. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  77121. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  77122. var t0 = performance.now();
  77123. for (var i = 0; i !== internalSteps; i++) {
  77124. this.internalStep(dt);
  77125. if (performance.now() - t0 > dt * 1000) {
  77126. break;
  77127. }
  77128. }
  77129. this.time += timeSinceLastCalled;
  77130. var h = this.time % dt;
  77131. var h_div_dt = h / dt;
  77132. var interpvelo = step_tmp1;
  77133. var bodies = this.bodies;
  77134. for (var j = 0; j !== bodies.length; j++) {
  77135. var b = bodies[j];
  77136. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  77137. b.position.vsub(b.previousPosition, interpvelo);
  77138. interpvelo.scale(h_div_dt, interpvelo);
  77139. b.position.vadd(interpvelo, b.interpolatedPosition);
  77140. }
  77141. else {
  77142. b.interpolatedPosition.copy(b.position);
  77143. b.interpolatedQuaternion.copy(b.quaternion);
  77144. }
  77145. }
  77146. }
  77147. };
  77148. };
  77149. return CannonJSPlugin;
  77150. }());
  77151. BABYLON.CannonJSPlugin = CannonJSPlugin;
  77152. })(BABYLON || (BABYLON = {}));
  77153. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  77154. var BABYLON;
  77155. (function (BABYLON) {
  77156. var OimoJSPlugin = /** @class */ (function () {
  77157. function OimoJSPlugin(iterations) {
  77158. this.name = "OimoJSPlugin";
  77159. this._tmpImpostorsArray = [];
  77160. this._tmpPositionVector = BABYLON.Vector3.Zero();
  77161. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  77162. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  77163. this.world.worldscale(1);
  77164. this.world.clear();
  77165. //making sure no stats are calculated
  77166. this.world.isNoStat = true;
  77167. }
  77168. OimoJSPlugin.prototype.setGravity = function (gravity) {
  77169. this.world.gravity.copy(gravity);
  77170. };
  77171. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  77172. this.world.timeStep = timeStep;
  77173. };
  77174. OimoJSPlugin.prototype.getTimeStep = function () {
  77175. return this.world.timeStep;
  77176. };
  77177. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  77178. var _this = this;
  77179. impostors.forEach(function (impostor) {
  77180. impostor.beforeStep();
  77181. });
  77182. this.world.step();
  77183. impostors.forEach(function (impostor) {
  77184. impostor.afterStep();
  77185. //update the ordered impostors array
  77186. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  77187. });
  77188. //check for collisions
  77189. var contact = this.world.contacts;
  77190. while (contact !== null) {
  77191. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  77192. contact = contact.next;
  77193. continue;
  77194. }
  77195. //is this body colliding with any other? get the impostor
  77196. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  77197. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  77198. if (!mainImpostor || !collidingImpostor) {
  77199. contact = contact.next;
  77200. continue;
  77201. }
  77202. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  77203. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  77204. contact = contact.next;
  77205. }
  77206. };
  77207. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77208. var mass = impostor.physicsBody.massInfo.mass;
  77209. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  77210. };
  77211. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77212. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  77213. this.applyImpulse(impostor, force, contactPoint);
  77214. };
  77215. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77216. var _this = this;
  77217. //parent-child relationship. Does this impostor has a parent impostor?
  77218. if (impostor.parent) {
  77219. if (impostor.physicsBody) {
  77220. this.removePhysicsBody(impostor);
  77221. //TODO is that needed?
  77222. impostor.forceUpdate();
  77223. }
  77224. return;
  77225. }
  77226. if (impostor.isBodyInitRequired()) {
  77227. var bodyConfig = {
  77228. name: impostor.uniqueId,
  77229. //Oimo must have mass, also for static objects.
  77230. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  77231. size: [],
  77232. type: [],
  77233. pos: [],
  77234. rot: [],
  77235. move: impostor.getParam("mass") !== 0,
  77236. //Supporting older versions of Oimo
  77237. world: this.world
  77238. };
  77239. var impostors = [impostor];
  77240. var addToArray = function (parent) {
  77241. if (!parent.getChildMeshes)
  77242. return;
  77243. parent.getChildMeshes().forEach(function (m) {
  77244. if (m.physicsImpostor) {
  77245. impostors.push(m.physicsImpostor);
  77246. //m.physicsImpostor._init();
  77247. }
  77248. });
  77249. };
  77250. addToArray(impostor.object);
  77251. var checkWithEpsilon_1 = function (value) {
  77252. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  77253. };
  77254. impostors.forEach(function (i) {
  77255. if (!impostor.object.rotationQuaternion) {
  77256. return;
  77257. }
  77258. //get the correct bounding box
  77259. var oldQuaternion = i.object.rotationQuaternion;
  77260. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  77261. x: impostor.object.rotationQuaternion.x,
  77262. y: impostor.object.rotationQuaternion.y,
  77263. z: impostor.object.rotationQuaternion.z,
  77264. s: impostor.object.rotationQuaternion.w
  77265. });
  77266. var extendSize = i.getObjectExtendSize();
  77267. if (i === impostor) {
  77268. var center = impostor.getObjectCenter();
  77269. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  77270. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  77271. //Can also use Array.prototype.push.apply
  77272. bodyConfig.pos.push(center.x);
  77273. bodyConfig.pos.push(center.y);
  77274. bodyConfig.pos.push(center.z);
  77275. //tmp solution
  77276. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77277. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77278. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  77279. }
  77280. else {
  77281. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  77282. bodyConfig.pos.push(localPosition.x);
  77283. bodyConfig.pos.push(localPosition.y);
  77284. bodyConfig.pos.push(localPosition.z);
  77285. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  77286. bodyConfig.rot.push(0);
  77287. bodyConfig.rot.push(0);
  77288. bodyConfig.rot.push(0);
  77289. }
  77290. // register mesh
  77291. switch (i.type) {
  77292. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77293. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  77294. case BABYLON.PhysicsImpostor.SphereImpostor:
  77295. var radiusX = extendSize.x;
  77296. var radiusY = extendSize.y;
  77297. var radiusZ = extendSize.z;
  77298. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  77299. bodyConfig.type.push('sphere');
  77300. //due to the way oimo works with compounds, add 3 times
  77301. bodyConfig.size.push(size);
  77302. bodyConfig.size.push(size);
  77303. bodyConfig.size.push(size);
  77304. break;
  77305. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77306. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  77307. var sizeY = checkWithEpsilon_1(extendSize.y);
  77308. bodyConfig.type.push('cylinder');
  77309. bodyConfig.size.push(sizeX);
  77310. bodyConfig.size.push(sizeY);
  77311. //due to the way oimo works with compounds, add one more value.
  77312. bodyConfig.size.push(sizeY);
  77313. break;
  77314. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77315. case BABYLON.PhysicsImpostor.BoxImpostor:
  77316. default:
  77317. var sizeX = checkWithEpsilon_1(extendSize.x);
  77318. var sizeY = checkWithEpsilon_1(extendSize.y);
  77319. var sizeZ = checkWithEpsilon_1(extendSize.z);
  77320. bodyConfig.type.push('box');
  77321. bodyConfig.size.push(sizeX);
  77322. bodyConfig.size.push(sizeY);
  77323. bodyConfig.size.push(sizeZ);
  77324. break;
  77325. }
  77326. //actually not needed, but hey...
  77327. i.object.rotationQuaternion = oldQuaternion;
  77328. });
  77329. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  77330. }
  77331. else {
  77332. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  77333. }
  77334. impostor.setDeltaPosition(this._tmpPositionVector);
  77335. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  77336. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  77337. };
  77338. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77339. //impostor.physicsBody.dispose();
  77340. //Same as : (older oimo versions)
  77341. this.world.removeRigidBody(impostor.physicsBody);
  77342. };
  77343. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77344. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77345. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77346. if (!mainBody || !connectedBody) {
  77347. return;
  77348. }
  77349. var jointData = impostorJoint.joint.jointData;
  77350. var options = jointData.nativeParams || {};
  77351. var type;
  77352. var nativeJointData = {
  77353. body1: mainBody,
  77354. body2: connectedBody,
  77355. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  77356. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  77357. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  77358. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  77359. min: options.min,
  77360. max: options.max,
  77361. collision: options.collision || jointData.collision,
  77362. spring: options.spring,
  77363. //supporting older version of Oimo
  77364. world: this.world
  77365. };
  77366. switch (impostorJoint.joint.type) {
  77367. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77368. type = "jointBall";
  77369. break;
  77370. case BABYLON.PhysicsJoint.SpringJoint:
  77371. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  77372. var springData = jointData;
  77373. nativeJointData.min = springData.length || nativeJointData.min;
  77374. //Max should also be set, just make sure it is at least min
  77375. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  77376. case BABYLON.PhysicsJoint.DistanceJoint:
  77377. type = "jointDistance";
  77378. nativeJointData.max = jointData.maxDistance;
  77379. break;
  77380. case BABYLON.PhysicsJoint.PrismaticJoint:
  77381. type = "jointPrisme";
  77382. break;
  77383. case BABYLON.PhysicsJoint.SliderJoint:
  77384. type = "jointSlide";
  77385. break;
  77386. case BABYLON.PhysicsJoint.WheelJoint:
  77387. type = "jointWheel";
  77388. break;
  77389. case BABYLON.PhysicsJoint.HingeJoint:
  77390. default:
  77391. type = "jointHinge";
  77392. break;
  77393. }
  77394. nativeJointData.type = type;
  77395. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  77396. };
  77397. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77398. //Bug in Oimo prevents us from disposing a joint in the playground
  77399. //joint.joint.physicsJoint.dispose();
  77400. //So we will bruteforce it!
  77401. try {
  77402. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  77403. }
  77404. catch (e) {
  77405. BABYLON.Tools.Warn(e);
  77406. }
  77407. };
  77408. OimoJSPlugin.prototype.isSupported = function () {
  77409. return this.BJSOIMO !== undefined;
  77410. };
  77411. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77412. if (!impostor.physicsBody.sleeping) {
  77413. //TODO check that
  77414. if (impostor.physicsBody.shapes.next) {
  77415. var parentShape = this._getLastShape(impostor.physicsBody);
  77416. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  77417. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  77418. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  77419. }
  77420. else {
  77421. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  77422. }
  77423. if (impostor.object.rotationQuaternion) {
  77424. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  77425. impostor.object.rotationQuaternion.normalize();
  77426. }
  77427. }
  77428. };
  77429. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77430. var body = impostor.physicsBody;
  77431. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  77432. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  77433. body.syncShapes();
  77434. body.awake();
  77435. };
  77436. OimoJSPlugin.prototype._getLastShape = function (body) {
  77437. var lastShape = body.shapes;
  77438. while (lastShape.next) {
  77439. lastShape = lastShape.next;
  77440. }
  77441. return lastShape;
  77442. };
  77443. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77444. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  77445. };
  77446. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77447. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  77448. };
  77449. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77450. var v = impostor.physicsBody.linearVelocity;
  77451. if (!v) {
  77452. return null;
  77453. }
  77454. return new BABYLON.Vector3(v.x, v.y, v.z);
  77455. };
  77456. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77457. var v = impostor.physicsBody.angularVelocity;
  77458. if (!v) {
  77459. return null;
  77460. }
  77461. return new BABYLON.Vector3(v.x, v.y, v.z);
  77462. };
  77463. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77464. var staticBody = mass === 0;
  77465. //this will actually set the body's density and not its mass.
  77466. //But this is how oimo treats the mass variable.
  77467. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  77468. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  77469. };
  77470. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  77471. return impostor.physicsBody.shapes.density;
  77472. };
  77473. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  77474. return impostor.physicsBody.shapes.friction;
  77475. };
  77476. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77477. impostor.physicsBody.shapes.friction = friction;
  77478. };
  77479. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77480. return impostor.physicsBody.shapes.restitution;
  77481. };
  77482. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77483. impostor.physicsBody.shapes.restitution = restitution;
  77484. };
  77485. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  77486. impostor.physicsBody.sleep();
  77487. };
  77488. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  77489. impostor.physicsBody.awake();
  77490. };
  77491. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77492. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  77493. if (minDistance !== void 0) {
  77494. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  77495. }
  77496. };
  77497. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77498. //TODO separate rotational and transational motors.
  77499. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77500. if (motor) {
  77501. motor.setMotor(speed, maxForce);
  77502. }
  77503. };
  77504. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  77505. //TODO separate rotational and transational motors.
  77506. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  77507. if (motor) {
  77508. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  77509. }
  77510. };
  77511. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77512. var body = impostor.physicsBody;
  77513. mesh.position.x = body.position.x;
  77514. mesh.position.y = body.position.y;
  77515. mesh.position.z = body.position.z;
  77516. if (mesh.rotationQuaternion) {
  77517. mesh.rotationQuaternion.x = body.orientation.x;
  77518. mesh.rotationQuaternion.y = body.orientation.y;
  77519. mesh.rotationQuaternion.z = body.orientation.z;
  77520. mesh.rotationQuaternion.w = body.orientation.s;
  77521. }
  77522. };
  77523. OimoJSPlugin.prototype.getRadius = function (impostor) {
  77524. return impostor.physicsBody.shapes.radius;
  77525. };
  77526. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77527. var shape = impostor.physicsBody.shapes;
  77528. result.x = shape.halfWidth * 2;
  77529. result.y = shape.halfHeight * 2;
  77530. result.z = shape.halfDepth * 2;
  77531. };
  77532. OimoJSPlugin.prototype.dispose = function () {
  77533. this.world.clear();
  77534. };
  77535. return OimoJSPlugin;
  77536. }());
  77537. BABYLON.OimoJSPlugin = OimoJSPlugin;
  77538. })(BABYLON || (BABYLON = {}));
  77539. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  77540. var BABYLON;
  77541. (function (BABYLON) {
  77542. /*
  77543. * Based on jsTGALoader - Javascript loader for TGA file
  77544. * By Vincent Thibault
  77545. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  77546. */
  77547. var TGATools = /** @class */ (function () {
  77548. function TGATools() {
  77549. }
  77550. TGATools.GetTGAHeader = function (data) {
  77551. var offset = 0;
  77552. var header = {
  77553. id_length: data[offset++],
  77554. colormap_type: data[offset++],
  77555. image_type: data[offset++],
  77556. colormap_index: data[offset++] | data[offset++] << 8,
  77557. colormap_length: data[offset++] | data[offset++] << 8,
  77558. colormap_size: data[offset++],
  77559. origin: [
  77560. data[offset++] | data[offset++] << 8,
  77561. data[offset++] | data[offset++] << 8
  77562. ],
  77563. width: data[offset++] | data[offset++] << 8,
  77564. height: data[offset++] | data[offset++] << 8,
  77565. pixel_size: data[offset++],
  77566. flags: data[offset++]
  77567. };
  77568. return header;
  77569. };
  77570. TGATools.UploadContent = function (gl, data) {
  77571. // Not enough data to contain header ?
  77572. if (data.length < 19) {
  77573. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  77574. return;
  77575. }
  77576. // Read Header
  77577. var offset = 18;
  77578. var header = TGATools.GetTGAHeader(data);
  77579. // Assume it's a valid Targa file.
  77580. if (header.id_length + offset > data.length) {
  77581. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  77582. return;
  77583. }
  77584. // Skip not needed data
  77585. offset += header.id_length;
  77586. var use_rle = false;
  77587. var use_pal = false;
  77588. var use_grey = false;
  77589. // Get some informations.
  77590. switch (header.image_type) {
  77591. case TGATools._TYPE_RLE_INDEXED:
  77592. use_rle = true;
  77593. case TGATools._TYPE_INDEXED:
  77594. use_pal = true;
  77595. break;
  77596. case TGATools._TYPE_RLE_RGB:
  77597. use_rle = true;
  77598. case TGATools._TYPE_RGB:
  77599. // use_rgb = true;
  77600. break;
  77601. case TGATools._TYPE_RLE_GREY:
  77602. use_rle = true;
  77603. case TGATools._TYPE_GREY:
  77604. use_grey = true;
  77605. break;
  77606. }
  77607. var pixel_data;
  77608. // var numAlphaBits = header.flags & 0xf;
  77609. var pixel_size = header.pixel_size >> 3;
  77610. var pixel_total = header.width * header.height * pixel_size;
  77611. // Read palettes
  77612. var palettes;
  77613. if (use_pal) {
  77614. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  77615. }
  77616. // Read LRE
  77617. if (use_rle) {
  77618. pixel_data = new Uint8Array(pixel_total);
  77619. var c, count, i;
  77620. var localOffset = 0;
  77621. var pixels = new Uint8Array(pixel_size);
  77622. while (offset < pixel_total && localOffset < pixel_total) {
  77623. c = data[offset++];
  77624. count = (c & 0x7f) + 1;
  77625. // RLE pixels
  77626. if (c & 0x80) {
  77627. // Bind pixel tmp array
  77628. for (i = 0; i < pixel_size; ++i) {
  77629. pixels[i] = data[offset++];
  77630. }
  77631. // Copy pixel array
  77632. for (i = 0; i < count; ++i) {
  77633. pixel_data.set(pixels, localOffset + i * pixel_size);
  77634. }
  77635. localOffset += pixel_size * count;
  77636. }
  77637. else {
  77638. count *= pixel_size;
  77639. for (i = 0; i < count; ++i) {
  77640. pixel_data[localOffset + i] = data[offset++];
  77641. }
  77642. localOffset += count;
  77643. }
  77644. }
  77645. }
  77646. else {
  77647. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  77648. }
  77649. // Load to texture
  77650. var x_start, y_start, x_step, y_step, y_end, x_end;
  77651. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  77652. default:
  77653. case TGATools._ORIGIN_UL:
  77654. x_start = 0;
  77655. x_step = 1;
  77656. x_end = header.width;
  77657. y_start = 0;
  77658. y_step = 1;
  77659. y_end = header.height;
  77660. break;
  77661. case TGATools._ORIGIN_BL:
  77662. x_start = 0;
  77663. x_step = 1;
  77664. x_end = header.width;
  77665. y_start = header.height - 1;
  77666. y_step = -1;
  77667. y_end = -1;
  77668. break;
  77669. case TGATools._ORIGIN_UR:
  77670. x_start = header.width - 1;
  77671. x_step = -1;
  77672. x_end = -1;
  77673. y_start = 0;
  77674. y_step = 1;
  77675. y_end = header.height;
  77676. break;
  77677. case TGATools._ORIGIN_BR:
  77678. x_start = header.width - 1;
  77679. x_step = -1;
  77680. x_end = -1;
  77681. y_start = header.height - 1;
  77682. y_step = -1;
  77683. y_end = -1;
  77684. break;
  77685. }
  77686. // Load the specify method
  77687. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  77688. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  77689. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  77690. };
  77691. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77692. var image = pixel_data, colormap = palettes;
  77693. var width = header.width, height = header.height;
  77694. var color, i = 0, x, y;
  77695. var imageData = new Uint8Array(width * height * 4);
  77696. for (y = y_start; y !== y_end; y += y_step) {
  77697. for (x = x_start; x !== x_end; x += x_step, i++) {
  77698. color = image[i];
  77699. imageData[(x + width * y) * 4 + 3] = 255;
  77700. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  77701. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  77702. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  77703. }
  77704. }
  77705. return imageData;
  77706. };
  77707. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77708. var image = pixel_data;
  77709. var width = header.width, height = header.height;
  77710. var color, i = 0, x, y;
  77711. var imageData = new Uint8Array(width * height * 4);
  77712. for (y = y_start; y !== y_end; y += y_step) {
  77713. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77714. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  77715. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  77716. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  77717. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  77718. imageData[(x + width * y) * 4 + 0] = r;
  77719. imageData[(x + width * y) * 4 + 1] = g;
  77720. imageData[(x + width * y) * 4 + 2] = b;
  77721. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  77722. }
  77723. }
  77724. return imageData;
  77725. };
  77726. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77727. var image = pixel_data;
  77728. var width = header.width, height = header.height;
  77729. var i = 0, x, y;
  77730. var imageData = new Uint8Array(width * height * 4);
  77731. for (y = y_start; y !== y_end; y += y_step) {
  77732. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  77733. imageData[(x + width * y) * 4 + 3] = 255;
  77734. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77735. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77736. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77737. }
  77738. }
  77739. return imageData;
  77740. };
  77741. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77742. var image = pixel_data;
  77743. var width = header.width, height = header.height;
  77744. var i = 0, x, y;
  77745. var imageData = new Uint8Array(width * height * 4);
  77746. for (y = y_start; y !== y_end; y += y_step) {
  77747. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  77748. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77749. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77750. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77751. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  77752. }
  77753. }
  77754. return imageData;
  77755. };
  77756. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77757. var image = pixel_data;
  77758. var width = header.width, height = header.height;
  77759. var color, i = 0, x, y;
  77760. var imageData = new Uint8Array(width * height * 4);
  77761. for (y = y_start; y !== y_end; y += y_step) {
  77762. for (x = x_start; x !== x_end; x += x_step, i++) {
  77763. color = image[i];
  77764. imageData[(x + width * y) * 4 + 0] = color;
  77765. imageData[(x + width * y) * 4 + 1] = color;
  77766. imageData[(x + width * y) * 4 + 2] = color;
  77767. imageData[(x + width * y) * 4 + 3] = 255;
  77768. }
  77769. }
  77770. return imageData;
  77771. };
  77772. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77773. var image = pixel_data;
  77774. var width = header.width, height = header.height;
  77775. var i = 0, x, y;
  77776. var imageData = new Uint8Array(width * height * 4);
  77777. for (y = y_start; y !== y_end; y += y_step) {
  77778. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77779. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  77780. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  77781. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77782. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  77783. }
  77784. }
  77785. return imageData;
  77786. };
  77787. //private static _TYPE_NO_DATA = 0;
  77788. TGATools._TYPE_INDEXED = 1;
  77789. TGATools._TYPE_RGB = 2;
  77790. TGATools._TYPE_GREY = 3;
  77791. TGATools._TYPE_RLE_INDEXED = 9;
  77792. TGATools._TYPE_RLE_RGB = 10;
  77793. TGATools._TYPE_RLE_GREY = 11;
  77794. TGATools._ORIGIN_MASK = 0x30;
  77795. TGATools._ORIGIN_SHIFT = 0x04;
  77796. TGATools._ORIGIN_BL = 0x00;
  77797. TGATools._ORIGIN_BR = 0x01;
  77798. TGATools._ORIGIN_UL = 0x02;
  77799. TGATools._ORIGIN_UR = 0x03;
  77800. return TGATools;
  77801. }());
  77802. BABYLON.TGATools = TGATools;
  77803. })(BABYLON || (BABYLON = {}));
  77804. //# sourceMappingURL=babylon.tga.js.map
  77805. var BABYLON;
  77806. (function (BABYLON) {
  77807. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  77808. // All values and structures referenced from:
  77809. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  77810. var DDS_MAGIC = 0x20534444;
  77811. var
  77812. //DDSD_CAPS = 0x1,
  77813. //DDSD_HEIGHT = 0x2,
  77814. //DDSD_WIDTH = 0x4,
  77815. //DDSD_PITCH = 0x8,
  77816. //DDSD_PIXELFORMAT = 0x1000,
  77817. DDSD_MIPMAPCOUNT = 0x20000;
  77818. //DDSD_LINEARSIZE = 0x80000,
  77819. //DDSD_DEPTH = 0x800000;
  77820. // var DDSCAPS_COMPLEX = 0x8,
  77821. // DDSCAPS_MIPMAP = 0x400000,
  77822. // DDSCAPS_TEXTURE = 0x1000;
  77823. var DDSCAPS2_CUBEMAP = 0x200;
  77824. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  77825. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  77826. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  77827. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  77828. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  77829. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  77830. // DDSCAPS2_VOLUME = 0x200000;
  77831. var
  77832. //DDPF_ALPHAPIXELS = 0x1,
  77833. //DDPF_ALPHA = 0x2,
  77834. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  77835. //DDPF_YUV = 0x200,
  77836. DDPF_LUMINANCE = 0x20000;
  77837. function FourCCToInt32(value) {
  77838. return value.charCodeAt(0) +
  77839. (value.charCodeAt(1) << 8) +
  77840. (value.charCodeAt(2) << 16) +
  77841. (value.charCodeAt(3) << 24);
  77842. }
  77843. function Int32ToFourCC(value) {
  77844. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  77845. }
  77846. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  77847. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  77848. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  77849. var FOURCC_DX10 = FourCCToInt32("DX10");
  77850. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  77851. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  77852. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  77853. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  77854. var headerLengthInt = 31; // The header length in 32 bit ints
  77855. // Offsets into the header array
  77856. var off_magic = 0;
  77857. var off_size = 1;
  77858. var off_flags = 2;
  77859. var off_height = 3;
  77860. var off_width = 4;
  77861. var off_mipmapCount = 7;
  77862. var off_pfFlags = 20;
  77863. var off_pfFourCC = 21;
  77864. var off_RGBbpp = 22;
  77865. var off_RMask = 23;
  77866. var off_GMask = 24;
  77867. var off_BMask = 25;
  77868. var off_AMask = 26;
  77869. // var off_caps1 = 27;
  77870. var off_caps2 = 28;
  77871. // var off_caps3 = 29;
  77872. // var off_caps4 = 30;
  77873. var off_dxgiFormat = 32;
  77874. ;
  77875. var DDSTools = /** @class */ (function () {
  77876. function DDSTools() {
  77877. }
  77878. DDSTools.GetDDSInfo = function (arrayBuffer) {
  77879. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77880. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  77881. var mipmapCount = 1;
  77882. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  77883. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77884. }
  77885. var fourCC = header[off_pfFourCC];
  77886. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  77887. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77888. switch (fourCC) {
  77889. case FOURCC_D3DFMT_R16G16B16A16F:
  77890. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77891. break;
  77892. case FOURCC_D3DFMT_R32G32B32A32F:
  77893. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77894. break;
  77895. case FOURCC_DX10:
  77896. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  77897. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77898. break;
  77899. }
  77900. }
  77901. return {
  77902. width: header[off_width],
  77903. height: header[off_height],
  77904. mipmapCount: mipmapCount,
  77905. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  77906. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  77907. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  77908. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  77909. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  77910. dxgiFormat: dxgiFormat,
  77911. textureType: textureType
  77912. };
  77913. };
  77914. DDSTools._ToHalfFloat = function (value) {
  77915. if (!DDSTools._FloatView) {
  77916. DDSTools._FloatView = new Float32Array(1);
  77917. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  77918. }
  77919. DDSTools._FloatView[0] = value;
  77920. var x = DDSTools._Int32View[0];
  77921. var bits = (x >> 16) & 0x8000; /* Get the sign */
  77922. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  77923. var e = (x >> 23) & 0xff; /* Using int is faster here */
  77924. /* If zero, or denormal, or exponent underflows too much for a denormal
  77925. * half, return signed zero. */
  77926. if (e < 103) {
  77927. return bits;
  77928. }
  77929. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  77930. if (e > 142) {
  77931. bits |= 0x7c00;
  77932. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  77933. * not Inf, so make sure we set one mantissa bit too. */
  77934. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  77935. return bits;
  77936. }
  77937. /* If exponent underflows but not too much, return a denormal */
  77938. if (e < 113) {
  77939. m |= 0x0800;
  77940. /* Extra rounding may overflow and set mantissa to 0 and exponent
  77941. * to 1, which is OK. */
  77942. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  77943. return bits;
  77944. }
  77945. bits |= ((e - 112) << 10) | (m >> 1);
  77946. bits += m & 1;
  77947. return bits;
  77948. };
  77949. DDSTools._FromHalfFloat = function (value) {
  77950. var s = (value & 0x8000) >> 15;
  77951. var e = (value & 0x7C00) >> 10;
  77952. var f = value & 0x03FF;
  77953. if (e === 0) {
  77954. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  77955. }
  77956. else if (e == 0x1F) {
  77957. return f ? NaN : ((s ? -1 : 1) * Infinity);
  77958. }
  77959. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  77960. };
  77961. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77962. var destArray = new Float32Array(dataLength);
  77963. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77964. var index = 0;
  77965. for (var y = 0; y < height; y++) {
  77966. for (var x = 0; x < width; x++) {
  77967. var srcPos = (x + y * width) * 4;
  77968. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  77969. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  77970. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  77971. if (DDSTools.StoreLODInAlphaChannel) {
  77972. destArray[index + 3] = lod;
  77973. }
  77974. else {
  77975. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  77976. }
  77977. index += 4;
  77978. }
  77979. }
  77980. return destArray;
  77981. };
  77982. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77983. if (DDSTools.StoreLODInAlphaChannel) {
  77984. var destArray = new Uint16Array(dataLength);
  77985. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77986. var index = 0;
  77987. for (var y = 0; y < height; y++) {
  77988. for (var x = 0; x < width; x++) {
  77989. var srcPos = (x + y * width) * 4;
  77990. destArray[index] = srcData[srcPos];
  77991. destArray[index + 1] = srcData[srcPos + 1];
  77992. destArray[index + 2] = srcData[srcPos + 2];
  77993. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  77994. index += 4;
  77995. }
  77996. }
  77997. return destArray;
  77998. }
  77999. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  78000. };
  78001. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78002. if (DDSTools.StoreLODInAlphaChannel) {
  78003. var destArray = new Float32Array(dataLength);
  78004. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78005. var index = 0;
  78006. for (var y = 0; y < height; y++) {
  78007. for (var x = 0; x < width; x++) {
  78008. var srcPos = (x + y * width) * 4;
  78009. destArray[index] = srcData[srcPos];
  78010. destArray[index + 1] = srcData[srcPos + 1];
  78011. destArray[index + 2] = srcData[srcPos + 2];
  78012. destArray[index + 3] = lod;
  78013. index += 4;
  78014. }
  78015. }
  78016. return destArray;
  78017. }
  78018. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  78019. };
  78020. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78021. var destArray = new Uint8Array(dataLength);
  78022. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78023. var index = 0;
  78024. for (var y = 0; y < height; y++) {
  78025. for (var x = 0; x < width; x++) {
  78026. var srcPos = (x + y * width) * 4;
  78027. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  78028. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  78029. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  78030. if (DDSTools.StoreLODInAlphaChannel) {
  78031. destArray[index + 3] = lod;
  78032. }
  78033. else {
  78034. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  78035. }
  78036. index += 4;
  78037. }
  78038. }
  78039. return destArray;
  78040. };
  78041. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78042. var destArray = new Uint8Array(dataLength);
  78043. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78044. var index = 0;
  78045. for (var y = 0; y < height; y++) {
  78046. for (var x = 0; x < width; x++) {
  78047. var srcPos = (x + y * width) * 4;
  78048. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  78049. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  78050. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  78051. if (DDSTools.StoreLODInAlphaChannel) {
  78052. destArray[index + 3] = lod;
  78053. }
  78054. else {
  78055. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  78056. }
  78057. index += 4;
  78058. }
  78059. }
  78060. return destArray;
  78061. };
  78062. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  78063. var byteArray = new Uint8Array(dataLength);
  78064. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78065. var index = 0;
  78066. for (var y = 0; y < height; y++) {
  78067. for (var x = 0; x < width; x++) {
  78068. var srcPos = (x + y * width) * 4;
  78069. byteArray[index] = srcData[srcPos + rOffset];
  78070. byteArray[index + 1] = srcData[srcPos + gOffset];
  78071. byteArray[index + 2] = srcData[srcPos + bOffset];
  78072. byteArray[index + 3] = srcData[srcPos + aOffset];
  78073. index += 4;
  78074. }
  78075. }
  78076. return byteArray;
  78077. };
  78078. DDSTools._ExtractLongWordOrder = function (value) {
  78079. if (value === 0 || value === 255 || value === -16777216) {
  78080. return 0;
  78081. }
  78082. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  78083. };
  78084. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  78085. var byteArray = new Uint8Array(dataLength);
  78086. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78087. var index = 0;
  78088. for (var y = 0; y < height; y++) {
  78089. for (var x = 0; x < width; x++) {
  78090. var srcPos = (x + y * width) * 3;
  78091. byteArray[index] = srcData[srcPos + rOffset];
  78092. byteArray[index + 1] = srcData[srcPos + gOffset];
  78093. byteArray[index + 2] = srcData[srcPos + bOffset];
  78094. index += 3;
  78095. }
  78096. }
  78097. return byteArray;
  78098. };
  78099. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  78100. var byteArray = new Uint8Array(dataLength);
  78101. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78102. var index = 0;
  78103. for (var y = 0; y < height; y++) {
  78104. for (var x = 0; x < width; x++) {
  78105. var srcPos = (x + y * width);
  78106. byteArray[index] = srcData[srcPos];
  78107. index++;
  78108. }
  78109. }
  78110. return byteArray;
  78111. };
  78112. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  78113. if (lodIndex === void 0) { lodIndex = -1; }
  78114. var ext = engine.getCaps().s3tc;
  78115. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78116. var fourCC, width, height, dataLength = 0, dataOffset;
  78117. var byteArray, mipmapCount, mip;
  78118. var internalFormat = 0;
  78119. var format = 0;
  78120. var blockBytes = 1;
  78121. if (header[off_magic] !== DDS_MAGIC) {
  78122. BABYLON.Tools.Error("Invalid magic number in DDS header");
  78123. return;
  78124. }
  78125. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  78126. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  78127. return;
  78128. }
  78129. if (info.isCompressed && !ext) {
  78130. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  78131. return;
  78132. }
  78133. var bpp = header[off_RGBbpp];
  78134. dataOffset = header[off_size] + 4;
  78135. var computeFormats = false;
  78136. if (info.isFourCC) {
  78137. fourCC = header[off_pfFourCC];
  78138. switch (fourCC) {
  78139. case FOURCC_DXT1:
  78140. blockBytes = 8;
  78141. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  78142. break;
  78143. case FOURCC_DXT3:
  78144. blockBytes = 16;
  78145. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  78146. break;
  78147. case FOURCC_DXT5:
  78148. blockBytes = 16;
  78149. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  78150. break;
  78151. case FOURCC_D3DFMT_R16G16B16A16F:
  78152. computeFormats = true;
  78153. break;
  78154. case FOURCC_D3DFMT_R32G32B32A32F:
  78155. computeFormats = true;
  78156. break;
  78157. case FOURCC_DX10:
  78158. // There is an additionnal header so dataOffset need to be changed
  78159. dataOffset += 5 * 4; // 5 uints
  78160. var supported = false;
  78161. switch (info.dxgiFormat) {
  78162. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  78163. computeFormats = true;
  78164. supported = true;
  78165. break;
  78166. case DXGI_FORMAT_B8G8R8X8_UNORM:
  78167. info.isRGB = true;
  78168. info.isFourCC = false;
  78169. bpp = 32;
  78170. supported = true;
  78171. break;
  78172. }
  78173. if (supported) {
  78174. break;
  78175. }
  78176. default:
  78177. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  78178. return;
  78179. }
  78180. }
  78181. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  78182. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  78183. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  78184. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  78185. if (computeFormats) {
  78186. format = engine._getWebGLTextureType(info.textureType);
  78187. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78188. }
  78189. mipmapCount = 1;
  78190. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  78191. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78192. }
  78193. for (var face = 0; face < faces; face++) {
  78194. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  78195. width = header[off_width];
  78196. height = header[off_height];
  78197. for (mip = 0; mip < mipmapCount; ++mip) {
  78198. if (lodIndex === -1 || lodIndex === mip) {
  78199. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  78200. var i = (lodIndex === -1) ? mip : 0;
  78201. if (!info.isCompressed && info.isFourCC) {
  78202. dataLength = width * height * 4;
  78203. var floatArray = null;
  78204. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  78205. if (bpp === 128) {
  78206. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78207. }
  78208. else if (bpp === 64) {
  78209. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78210. }
  78211. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78212. format = engine._getWebGLTextureType(info.textureType);
  78213. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78214. }
  78215. else {
  78216. if (bpp === 128) {
  78217. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78218. }
  78219. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  78220. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78221. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78222. format = engine._getWebGLTextureType(info.textureType);
  78223. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  78224. }
  78225. else {
  78226. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  78227. }
  78228. }
  78229. if (floatArray) {
  78230. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  78231. }
  78232. }
  78233. else if (info.isRGB) {
  78234. if (bpp === 24) {
  78235. dataLength = width * height * 3;
  78236. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  78237. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  78238. }
  78239. else {
  78240. dataLength = width * height * 4;
  78241. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  78242. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  78243. }
  78244. }
  78245. else if (info.isLuminance) {
  78246. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  78247. var unpaddedRowSize = width;
  78248. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  78249. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  78250. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  78251. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  78252. }
  78253. else {
  78254. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  78255. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  78256. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  78257. }
  78258. }
  78259. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  78260. width *= 0.5;
  78261. height *= 0.5;
  78262. width = Math.max(1.0, width);
  78263. height = Math.max(1.0, height);
  78264. }
  78265. if (currentFace !== undefined) {
  78266. // Loading a single face
  78267. break;
  78268. }
  78269. }
  78270. };
  78271. DDSTools.StoreLODInAlphaChannel = false;
  78272. return DDSTools;
  78273. }());
  78274. BABYLON.DDSTools = DDSTools;
  78275. })(BABYLON || (BABYLON = {}));
  78276. //# sourceMappingURL=babylon.dds.js.map
  78277. var BABYLON;
  78278. (function (BABYLON) {
  78279. /**
  78280. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  78281. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  78282. */
  78283. var KhronosTextureContainer = /** @class */ (function () {
  78284. /**
  78285. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  78286. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  78287. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  78288. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  78289. */
  78290. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  78291. this.arrayBuffer = arrayBuffer;
  78292. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  78293. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  78294. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  78295. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  78296. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  78297. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  78298. BABYLON.Tools.Error("texture missing KTX identifier");
  78299. return;
  78300. }
  78301. // load the reset of the header in native 32 bit int
  78302. var header = new Int32Array(this.arrayBuffer, 12, 13);
  78303. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  78304. var oppositeEndianess = header[0] === 0x01020304;
  78305. // read all the header elements in order they exist in the file, without modification (sans endainness)
  78306. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  78307. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  78308. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  78309. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  78310. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  78311. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  78312. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  78313. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  78314. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  78315. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  78316. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  78317. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  78318. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  78319. if (this.glType !== 0) {
  78320. BABYLON.Tools.Error("only compressed formats currently supported");
  78321. return;
  78322. }
  78323. else {
  78324. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  78325. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  78326. }
  78327. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  78328. BABYLON.Tools.Error("only 2D textures currently supported");
  78329. return;
  78330. }
  78331. if (this.numberOfArrayElements !== 0) {
  78332. BABYLON.Tools.Error("texture arrays not currently supported");
  78333. return;
  78334. }
  78335. if (this.numberOfFaces !== facesExpected) {
  78336. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  78337. return;
  78338. }
  78339. // we now have a completely validated file, so could use existence of loadType as success
  78340. // would need to make this more elaborate & adjust checks above to support more than one load type
  78341. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  78342. }
  78343. // not as fast hardware based, but will probably never need to use
  78344. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  78345. return ((val & 0xFF) << 24)
  78346. | ((val & 0xFF00) << 8)
  78347. | ((val >> 8) & 0xFF00)
  78348. | ((val >> 24) & 0xFF);
  78349. };
  78350. /**
  78351. * It is assumed that the texture has already been created & is currently bound
  78352. */
  78353. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  78354. switch (this.loadType) {
  78355. case KhronosTextureContainer.COMPRESSED_2D:
  78356. this._upload2DCompressedLevels(gl, loadMipmaps);
  78357. break;
  78358. case KhronosTextureContainer.TEX_2D:
  78359. case KhronosTextureContainer.COMPRESSED_3D:
  78360. case KhronosTextureContainer.TEX_3D:
  78361. }
  78362. };
  78363. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  78364. // initialize width & height for level 1
  78365. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  78366. var width = this.pixelWidth;
  78367. var height = this.pixelHeight;
  78368. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  78369. for (var level = 0; level < mipmapCount; level++) {
  78370. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  78371. for (var face = 0; face < this.numberOfFaces; face++) {
  78372. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  78373. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  78374. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  78375. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  78376. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  78377. }
  78378. width = Math.max(1.0, width * 0.5);
  78379. height = Math.max(1.0, height * 0.5);
  78380. }
  78381. };
  78382. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  78383. // load types
  78384. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  78385. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  78386. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  78387. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  78388. return KhronosTextureContainer;
  78389. }());
  78390. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  78391. })(BABYLON || (BABYLON = {}));
  78392. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  78393. var BABYLON;
  78394. (function (BABYLON) {
  78395. var Debug = /** @class */ (function () {
  78396. function Debug() {
  78397. }
  78398. Debug.AxesViewer = /** @class */ (function () {
  78399. function AxesViewer(scene, scaleLines) {
  78400. if (scaleLines === void 0) { scaleLines = 1; }
  78401. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78402. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78403. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78404. this.scaleLines = 1;
  78405. this.scaleLines = scaleLines;
  78406. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  78407. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  78408. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  78409. this._xmesh.renderingGroupId = 2;
  78410. this._ymesh.renderingGroupId = 2;
  78411. this._zmesh.renderingGroupId = 2;
  78412. this._xmesh.material.checkReadyOnlyOnce = true;
  78413. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  78414. this._ymesh.material.checkReadyOnlyOnce = true;
  78415. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  78416. this._zmesh.material.checkReadyOnlyOnce = true;
  78417. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  78418. this.scene = scene;
  78419. }
  78420. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  78421. var scaleLines = this.scaleLines;
  78422. if (this._xmesh) {
  78423. this._xmesh.position.copyFrom(position);
  78424. }
  78425. if (this._ymesh) {
  78426. this._ymesh.position.copyFrom(position);
  78427. }
  78428. if (this._zmesh) {
  78429. this._zmesh.position.copyFrom(position);
  78430. }
  78431. var point2 = this._xline[1];
  78432. point2.x = xaxis.x * scaleLines;
  78433. point2.y = xaxis.y * scaleLines;
  78434. point2.z = xaxis.z * scaleLines;
  78435. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  78436. point2 = this._yline[1];
  78437. point2.x = yaxis.x * scaleLines;
  78438. point2.y = yaxis.y * scaleLines;
  78439. point2.z = yaxis.z * scaleLines;
  78440. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  78441. point2 = this._zline[1];
  78442. point2.x = zaxis.x * scaleLines;
  78443. point2.y = zaxis.y * scaleLines;
  78444. point2.z = zaxis.z * scaleLines;
  78445. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  78446. };
  78447. AxesViewer.prototype.dispose = function () {
  78448. if (this._xmesh) {
  78449. this._xmesh.dispose();
  78450. }
  78451. if (this._ymesh) {
  78452. this._ymesh.dispose();
  78453. }
  78454. if (this._zmesh) {
  78455. this._zmesh.dispose();
  78456. }
  78457. this._xmesh = null;
  78458. this._ymesh = null;
  78459. this._zmesh = null;
  78460. this.scene = null;
  78461. };
  78462. return AxesViewer;
  78463. }());
  78464. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  78465. __extends(BoneAxesViewer, _super);
  78466. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  78467. if (scaleLines === void 0) { scaleLines = 1; }
  78468. var _this = _super.call(this, scene, scaleLines) || this;
  78469. _this.pos = BABYLON.Vector3.Zero();
  78470. _this.xaxis = BABYLON.Vector3.Zero();
  78471. _this.yaxis = BABYLON.Vector3.Zero();
  78472. _this.zaxis = BABYLON.Vector3.Zero();
  78473. _this.mesh = mesh;
  78474. _this.bone = bone;
  78475. return _this;
  78476. }
  78477. BoneAxesViewer.prototype.update = function () {
  78478. if (!this.mesh || !this.bone) {
  78479. return;
  78480. }
  78481. var bone = this.bone;
  78482. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  78483. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  78484. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  78485. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  78486. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  78487. };
  78488. BoneAxesViewer.prototype.dispose = function () {
  78489. if (this.mesh) {
  78490. this.mesh = null;
  78491. this.bone = null;
  78492. _super.prototype.dispose.call(this);
  78493. }
  78494. };
  78495. return BoneAxesViewer;
  78496. }(Debug.AxesViewer));
  78497. Debug.PhysicsViewer = /** @class */ (function () {
  78498. function PhysicsViewer(scene) {
  78499. this._impostors = [];
  78500. this._meshes = [];
  78501. this._numMeshes = 0;
  78502. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78503. var physicEngine = this._scene.getPhysicsEngine();
  78504. if (physicEngine) {
  78505. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  78506. }
  78507. }
  78508. PhysicsViewer.prototype._updateDebugMeshes = function () {
  78509. var plugin = this._physicsEnginePlugin;
  78510. for (var i = 0; i < this._numMeshes; i++) {
  78511. var impostor = this._impostors[i];
  78512. if (!impostor) {
  78513. continue;
  78514. }
  78515. if (impostor.isDisposed) {
  78516. this.hideImpostor(this._impostors[i--]);
  78517. }
  78518. else {
  78519. var mesh = this._meshes[i];
  78520. if (mesh && plugin) {
  78521. plugin.syncMeshWithImpostor(mesh, impostor);
  78522. }
  78523. }
  78524. }
  78525. };
  78526. PhysicsViewer.prototype.showImpostor = function (impostor) {
  78527. if (!this._scene) {
  78528. return;
  78529. }
  78530. for (var i = 0; i < this._numMeshes; i++) {
  78531. if (this._impostors[i] == impostor) {
  78532. return;
  78533. }
  78534. }
  78535. var debugMesh = this._getDebugMesh(impostor, this._scene);
  78536. if (debugMesh) {
  78537. this._impostors[this._numMeshes] = impostor;
  78538. this._meshes[this._numMeshes] = debugMesh;
  78539. if (this._numMeshes === 0) {
  78540. this._renderFunction = this._updateDebugMeshes.bind(this);
  78541. this._scene.registerBeforeRender(this._renderFunction);
  78542. }
  78543. this._numMeshes++;
  78544. }
  78545. };
  78546. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  78547. if (!impostor || !this._scene) {
  78548. return;
  78549. }
  78550. var removed = false;
  78551. for (var i = 0; i < this._numMeshes; i++) {
  78552. if (this._impostors[i] == impostor) {
  78553. var mesh = this._meshes[i];
  78554. if (!mesh) {
  78555. continue;
  78556. }
  78557. this._scene.removeMesh(mesh);
  78558. mesh.dispose();
  78559. this._numMeshes--;
  78560. if (this._numMeshes > 0) {
  78561. this._meshes[i] = this._meshes[this._numMeshes];
  78562. this._impostors[i] = this._impostors[this._numMeshes];
  78563. this._meshes[this._numMeshes] = null;
  78564. this._impostors[this._numMeshes] = null;
  78565. }
  78566. else {
  78567. this._meshes[0] = null;
  78568. this._impostors[0] = null;
  78569. }
  78570. removed = true;
  78571. break;
  78572. }
  78573. }
  78574. if (removed && this._numMeshes === 0) {
  78575. this._scene.unregisterBeforeRender(this._renderFunction);
  78576. }
  78577. };
  78578. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  78579. if (!this._debugMaterial) {
  78580. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  78581. this._debugMaterial.wireframe = true;
  78582. }
  78583. return this._debugMaterial;
  78584. };
  78585. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  78586. if (!this._debugBoxMesh) {
  78587. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  78588. this._debugBoxMesh.renderingGroupId = 1;
  78589. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78590. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  78591. scene.removeMesh(this._debugBoxMesh);
  78592. }
  78593. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  78594. };
  78595. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  78596. if (!this._debugSphereMesh) {
  78597. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  78598. this._debugSphereMesh.renderingGroupId = 1;
  78599. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78600. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  78601. scene.removeMesh(this._debugSphereMesh);
  78602. }
  78603. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  78604. };
  78605. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  78606. var mesh = null;
  78607. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  78608. mesh = this._getDebugBoxMesh(scene);
  78609. impostor.getBoxSizeToRef(mesh.scaling);
  78610. }
  78611. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  78612. mesh = this._getDebugSphereMesh(scene);
  78613. var radius = impostor.getRadius();
  78614. mesh.scaling.x = radius * 2;
  78615. mesh.scaling.y = radius * 2;
  78616. mesh.scaling.z = radius * 2;
  78617. }
  78618. return mesh;
  78619. };
  78620. PhysicsViewer.prototype.dispose = function () {
  78621. for (var i = 0; i < this._numMeshes; i++) {
  78622. this.hideImpostor(this._impostors[i]);
  78623. }
  78624. if (this._debugBoxMesh) {
  78625. this._debugBoxMesh.dispose();
  78626. }
  78627. if (this._debugSphereMesh) {
  78628. this._debugSphereMesh.dispose();
  78629. }
  78630. if (this._debugMaterial) {
  78631. this._debugMaterial.dispose();
  78632. }
  78633. this._impostors.length = 0;
  78634. this._scene = null;
  78635. this._physicsEnginePlugin = null;
  78636. };
  78637. return PhysicsViewer;
  78638. }());
  78639. Debug.SkeletonViewer = /** @class */ (function () {
  78640. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  78641. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  78642. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  78643. this.skeleton = skeleton;
  78644. this.mesh = mesh;
  78645. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  78646. this.renderingGroupId = renderingGroupId;
  78647. this.color = BABYLON.Color3.White();
  78648. this._debugLines = new Array();
  78649. this._isEnabled = false;
  78650. this._scene = scene;
  78651. this.update();
  78652. this._renderFunction = this.update.bind(this);
  78653. }
  78654. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  78655. get: function () {
  78656. return this._isEnabled;
  78657. },
  78658. set: function (value) {
  78659. if (this._isEnabled === value) {
  78660. return;
  78661. }
  78662. this._isEnabled = value;
  78663. if (value) {
  78664. this._scene.registerBeforeRender(this._renderFunction);
  78665. }
  78666. else {
  78667. this._scene.unregisterBeforeRender(this._renderFunction);
  78668. }
  78669. },
  78670. enumerable: true,
  78671. configurable: true
  78672. });
  78673. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  78674. if (x === void 0) { x = 0; }
  78675. if (y === void 0) { y = 0; }
  78676. if (z === void 0) { z = 0; }
  78677. var tmat = BABYLON.Tmp.Matrix[0];
  78678. var parentBone = bone.getParent();
  78679. tmat.copyFrom(bone.getLocalMatrix());
  78680. if (x !== 0 || y !== 0 || z !== 0) {
  78681. var tmat2 = BABYLON.Tmp.Matrix[1];
  78682. BABYLON.Matrix.IdentityToRef(tmat2);
  78683. tmat2.m[12] = x;
  78684. tmat2.m[13] = y;
  78685. tmat2.m[14] = z;
  78686. tmat2.multiplyToRef(tmat, tmat);
  78687. }
  78688. if (parentBone) {
  78689. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  78690. }
  78691. tmat.multiplyToRef(meshMat, tmat);
  78692. position.x = tmat.m[12];
  78693. position.y = tmat.m[13];
  78694. position.z = tmat.m[14];
  78695. };
  78696. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  78697. var len = bones.length;
  78698. var meshPos = this.mesh.position;
  78699. for (var i = 0; i < len; i++) {
  78700. var bone = bones[i];
  78701. var points = this._debugLines[i];
  78702. if (!points) {
  78703. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78704. this._debugLines[i] = points;
  78705. }
  78706. this._getBonePosition(points[0], bone, meshMat);
  78707. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  78708. points[0].subtractInPlace(meshPos);
  78709. points[1].subtractInPlace(meshPos);
  78710. }
  78711. };
  78712. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  78713. var len = bones.length;
  78714. var boneNum = 0;
  78715. var meshPos = this.mesh.position;
  78716. for (var i = len - 1; i >= 0; i--) {
  78717. var childBone = bones[i];
  78718. var parentBone = childBone.getParent();
  78719. if (!parentBone) {
  78720. continue;
  78721. }
  78722. var points = this._debugLines[boneNum];
  78723. if (!points) {
  78724. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78725. this._debugLines[boneNum] = points;
  78726. }
  78727. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  78728. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  78729. points[0].subtractInPlace(meshPos);
  78730. points[1].subtractInPlace(meshPos);
  78731. boneNum++;
  78732. }
  78733. };
  78734. SkeletonViewer.prototype.update = function () {
  78735. if (this.autoUpdateBonesMatrices) {
  78736. this.skeleton.computeAbsoluteTransforms();
  78737. }
  78738. if (this.skeleton.bones[0].length === undefined) {
  78739. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78740. }
  78741. else {
  78742. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78743. }
  78744. if (!this._debugMesh) {
  78745. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  78746. this._debugMesh.renderingGroupId = this.renderingGroupId;
  78747. }
  78748. else {
  78749. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  78750. }
  78751. this._debugMesh.position.copyFrom(this.mesh.position);
  78752. this._debugMesh.color = this.color;
  78753. };
  78754. SkeletonViewer.prototype.dispose = function () {
  78755. if (this._debugMesh) {
  78756. this.isEnabled = false;
  78757. this._debugMesh.dispose();
  78758. this._debugMesh = null;
  78759. }
  78760. };
  78761. return SkeletonViewer;
  78762. }());
  78763. return Debug;
  78764. }());
  78765. BABYLON.Debug = Debug;
  78766. })(BABYLON || (BABYLON = {}));
  78767. //# sourceMappingURL=babylon.debugModules.js.map
  78768. var BABYLON;
  78769. (function (BABYLON) {
  78770. var RayHelper = /** @class */ (function () {
  78771. function RayHelper(ray) {
  78772. this.ray = ray;
  78773. }
  78774. RayHelper.CreateAndShow = function (ray, scene, color) {
  78775. var helper = new RayHelper(ray);
  78776. helper.show(scene, color);
  78777. return helper;
  78778. };
  78779. RayHelper.prototype.show = function (scene, color) {
  78780. if (!this._renderFunction && this.ray) {
  78781. var ray = this.ray;
  78782. this._renderFunction = this._render.bind(this);
  78783. this._scene = scene;
  78784. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  78785. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  78786. if (this._renderFunction) {
  78787. this._scene.registerBeforeRender(this._renderFunction);
  78788. }
  78789. }
  78790. if (color && this._renderLine) {
  78791. this._renderLine.color.copyFrom(color);
  78792. }
  78793. };
  78794. RayHelper.prototype.hide = function () {
  78795. if (this._renderFunction && this._scene) {
  78796. this._scene.unregisterBeforeRender(this._renderFunction);
  78797. this._scene = null;
  78798. this._renderFunction = null;
  78799. if (this._renderLine) {
  78800. this._renderLine.dispose();
  78801. this._renderLine = null;
  78802. }
  78803. this._renderPoints = [];
  78804. }
  78805. };
  78806. RayHelper.prototype._render = function () {
  78807. var ray = this.ray;
  78808. if (!ray) {
  78809. return;
  78810. }
  78811. var point = this._renderPoints[1];
  78812. var len = Math.min(ray.length, 1000000);
  78813. point.copyFrom(ray.direction);
  78814. point.scaleInPlace(len);
  78815. point.addInPlace(ray.origin);
  78816. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  78817. };
  78818. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  78819. this._attachedToMesh = mesh;
  78820. var ray = this.ray;
  78821. if (!ray) {
  78822. return;
  78823. }
  78824. if (!ray.direction) {
  78825. ray.direction = BABYLON.Vector3.Zero();
  78826. }
  78827. if (!ray.origin) {
  78828. ray.origin = BABYLON.Vector3.Zero();
  78829. }
  78830. if (length) {
  78831. ray.length = length;
  78832. }
  78833. if (!meshSpaceOrigin) {
  78834. meshSpaceOrigin = BABYLON.Vector3.Zero();
  78835. }
  78836. if (!meshSpaceDirection) {
  78837. // -1 so that this will work with Mesh.lookAt
  78838. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  78839. }
  78840. if (!this._meshSpaceDirection) {
  78841. this._meshSpaceDirection = meshSpaceDirection.clone();
  78842. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  78843. }
  78844. else {
  78845. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  78846. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  78847. }
  78848. if (!this._updateToMeshFunction) {
  78849. this._updateToMeshFunction = this._updateToMesh.bind(this);
  78850. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  78851. }
  78852. this._updateToMesh();
  78853. };
  78854. RayHelper.prototype.detachFromMesh = function () {
  78855. if (this._attachedToMesh) {
  78856. if (this._updateToMeshFunction) {
  78857. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  78858. }
  78859. this._attachedToMesh = null;
  78860. this._updateToMeshFunction = null;
  78861. }
  78862. };
  78863. RayHelper.prototype._updateToMesh = function () {
  78864. var ray = this.ray;
  78865. if (!this._attachedToMesh || !ray) {
  78866. return;
  78867. }
  78868. if (this._attachedToMesh._isDisposed) {
  78869. this.detachFromMesh();
  78870. return;
  78871. }
  78872. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  78873. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  78874. };
  78875. RayHelper.prototype.dispose = function () {
  78876. this.hide();
  78877. this.detachFromMesh();
  78878. this.ray = null;
  78879. };
  78880. return RayHelper;
  78881. }());
  78882. BABYLON.RayHelper = RayHelper;
  78883. })(BABYLON || (BABYLON = {}));
  78884. //# sourceMappingURL=babylon.rayHelper.js.map
  78885. var BABYLON;
  78886. (function (BABYLON) {
  78887. // load the inspector using require, if not present in the global namespace.
  78888. var DebugLayer = /** @class */ (function () {
  78889. function DebugLayer(scene) {
  78890. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78891. this._scene = scene;
  78892. // load inspector using require, if it doesn't exist on the global namespace.
  78893. }
  78894. /** Creates the inspector window. */
  78895. DebugLayer.prototype._createInspector = function (config) {
  78896. if (config === void 0) { config = {}; }
  78897. var popup = config.popup || false;
  78898. var initialTab = config.initialTab || 0;
  78899. var parentElement = config.parentElement || null;
  78900. if (!this._inspector) {
  78901. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78902. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  78903. } // else nothing to do,; instance is already existing
  78904. };
  78905. DebugLayer.prototype.isVisible = function () {
  78906. if (!this._inspector) {
  78907. return false;
  78908. }
  78909. return true;
  78910. };
  78911. DebugLayer.prototype.hide = function () {
  78912. if (this._inspector) {
  78913. try {
  78914. this._inspector.dispose();
  78915. }
  78916. catch (e) {
  78917. // If the inspector has been removed directly from the inspector tool
  78918. }
  78919. this._inspector = null;
  78920. }
  78921. };
  78922. DebugLayer.prototype.show = function (config) {
  78923. if (config === void 0) { config = {}; }
  78924. if (typeof this.BJSINSPECTOR == 'undefined') {
  78925. // Load inspector and add it to the DOM
  78926. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  78927. }
  78928. else {
  78929. // Otherwise creates the inspector
  78930. this._createInspector(config);
  78931. }
  78932. };
  78933. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  78934. return DebugLayer;
  78935. }());
  78936. BABYLON.DebugLayer = DebugLayer;
  78937. })(BABYLON || (BABYLON = {}));
  78938. //# sourceMappingURL=babylon.debugLayer.js.map
  78939. var BABYLON;
  78940. (function (BABYLON) {
  78941. var BoundingBoxRenderer = /** @class */ (function () {
  78942. function BoundingBoxRenderer(scene) {
  78943. this.frontColor = new BABYLON.Color3(1, 1, 1);
  78944. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  78945. this.showBackLines = true;
  78946. this.renderList = new BABYLON.SmartArray(32);
  78947. this._vertexBuffers = {};
  78948. this._scene = scene;
  78949. }
  78950. BoundingBoxRenderer.prototype._prepareRessources = function () {
  78951. if (this._colorShader) {
  78952. return;
  78953. }
  78954. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  78955. attributes: [BABYLON.VertexBuffer.PositionKind],
  78956. uniforms: ["world", "viewProjection", "color"]
  78957. });
  78958. var engine = this._scene.getEngine();
  78959. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  78960. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  78961. this._createIndexBuffer();
  78962. };
  78963. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  78964. var engine = this._scene.getEngine();
  78965. 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]);
  78966. };
  78967. BoundingBoxRenderer.prototype._rebuild = function () {
  78968. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78969. if (vb) {
  78970. vb._rebuild();
  78971. }
  78972. this._createIndexBuffer();
  78973. };
  78974. BoundingBoxRenderer.prototype.reset = function () {
  78975. this.renderList.reset();
  78976. };
  78977. BoundingBoxRenderer.prototype.render = function () {
  78978. if (this.renderList.length === 0) {
  78979. return;
  78980. }
  78981. this._prepareRessources();
  78982. if (!this._colorShader.isReady()) {
  78983. return;
  78984. }
  78985. var engine = this._scene.getEngine();
  78986. engine.setDepthWrite(false);
  78987. this._colorShader._preBind();
  78988. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  78989. var boundingBox = this.renderList.data[boundingBoxIndex];
  78990. var min = boundingBox.minimum;
  78991. var max = boundingBox.maximum;
  78992. var diff = max.subtract(min);
  78993. var median = min.add(diff.scale(0.5));
  78994. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78995. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78996. .multiply(boundingBox.getWorldMatrix());
  78997. // VBOs
  78998. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78999. if (this.showBackLines) {
  79000. // Back
  79001. engine.setDepthFunctionToGreaterOrEqual();
  79002. this._scene.resetCachedMaterial();
  79003. this._colorShader.setColor4("color", this.backColor.toColor4());
  79004. this._colorShader.bind(worldMatrix);
  79005. // Draw order
  79006. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79007. }
  79008. // Front
  79009. engine.setDepthFunctionToLess();
  79010. this._scene.resetCachedMaterial();
  79011. this._colorShader.setColor4("color", this.frontColor.toColor4());
  79012. this._colorShader.bind(worldMatrix);
  79013. // Draw order
  79014. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79015. }
  79016. this._colorShader.unbind();
  79017. engine.setDepthFunctionToLessOrEqual();
  79018. engine.setDepthWrite(true);
  79019. };
  79020. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  79021. this._prepareRessources();
  79022. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  79023. return;
  79024. }
  79025. var engine = this._scene.getEngine();
  79026. engine.setDepthWrite(false);
  79027. engine.setColorWrite(false);
  79028. this._colorShader._preBind();
  79029. var boundingBox = mesh._boundingInfo.boundingBox;
  79030. var min = boundingBox.minimum;
  79031. var max = boundingBox.maximum;
  79032. var diff = max.subtract(min);
  79033. var median = min.add(diff.scale(0.5));
  79034. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79035. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79036. .multiply(boundingBox.getWorldMatrix());
  79037. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79038. engine.setDepthFunctionToLess();
  79039. this._scene.resetCachedMaterial();
  79040. this._colorShader.bind(worldMatrix);
  79041. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79042. this._colorShader.unbind();
  79043. engine.setDepthFunctionToLessOrEqual();
  79044. engine.setDepthWrite(true);
  79045. engine.setColorWrite(true);
  79046. };
  79047. BoundingBoxRenderer.prototype.dispose = function () {
  79048. if (!this._colorShader) {
  79049. return;
  79050. }
  79051. this.renderList.dispose();
  79052. this._colorShader.dispose();
  79053. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79054. if (buffer) {
  79055. buffer.dispose();
  79056. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79057. }
  79058. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79059. };
  79060. return BoundingBoxRenderer;
  79061. }());
  79062. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  79063. })(BABYLON || (BABYLON = {}));
  79064. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  79065. var BABYLON;
  79066. (function (BABYLON) {
  79067. var MorphTarget = /** @class */ (function () {
  79068. function MorphTarget(name, influence) {
  79069. if (influence === void 0) { influence = 0; }
  79070. this.name = name;
  79071. this.animations = new Array();
  79072. this._positions = null;
  79073. this._normals = null;
  79074. this._tangents = null;
  79075. this.onInfluenceChanged = new BABYLON.Observable();
  79076. this.influence = influence;
  79077. }
  79078. Object.defineProperty(MorphTarget.prototype, "influence", {
  79079. get: function () {
  79080. return this._influence;
  79081. },
  79082. set: function (influence) {
  79083. if (this._influence === influence) {
  79084. return;
  79085. }
  79086. var previous = this._influence;
  79087. this._influence = influence;
  79088. if (this.onInfluenceChanged.hasObservers) {
  79089. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  79090. }
  79091. },
  79092. enumerable: true,
  79093. configurable: true
  79094. });
  79095. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  79096. get: function () {
  79097. return !!this._positions;
  79098. },
  79099. enumerable: true,
  79100. configurable: true
  79101. });
  79102. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  79103. get: function () {
  79104. return !!this._normals;
  79105. },
  79106. enumerable: true,
  79107. configurable: true
  79108. });
  79109. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  79110. get: function () {
  79111. return !!this._tangents;
  79112. },
  79113. enumerable: true,
  79114. configurable: true
  79115. });
  79116. MorphTarget.prototype.setPositions = function (data) {
  79117. this._positions = data;
  79118. };
  79119. MorphTarget.prototype.getPositions = function () {
  79120. return this._positions;
  79121. };
  79122. MorphTarget.prototype.setNormals = function (data) {
  79123. this._normals = data;
  79124. };
  79125. MorphTarget.prototype.getNormals = function () {
  79126. return this._normals;
  79127. };
  79128. MorphTarget.prototype.setTangents = function (data) {
  79129. this._tangents = data;
  79130. };
  79131. MorphTarget.prototype.getTangents = function () {
  79132. return this._tangents;
  79133. };
  79134. /**
  79135. * Serializes the current target into a Serialization object.
  79136. * Returns the serialized object.
  79137. */
  79138. MorphTarget.prototype.serialize = function () {
  79139. var serializationObject = {};
  79140. serializationObject.name = this.name;
  79141. serializationObject.influence = this.influence;
  79142. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  79143. if (this.hasNormals) {
  79144. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  79145. }
  79146. if (this.hasTangents) {
  79147. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  79148. }
  79149. // Animations
  79150. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  79151. return serializationObject;
  79152. };
  79153. // Statics
  79154. MorphTarget.Parse = function (serializationObject) {
  79155. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  79156. result.setPositions(serializationObject.positions);
  79157. if (serializationObject.normals) {
  79158. result.setNormals(serializationObject.normals);
  79159. }
  79160. if (serializationObject.tangents) {
  79161. result.setTangents(serializationObject.tangents);
  79162. }
  79163. // Animations
  79164. if (serializationObject.animations) {
  79165. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  79166. var parsedAnimation = serializationObject.animations[animationIndex];
  79167. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  79168. }
  79169. }
  79170. return result;
  79171. };
  79172. MorphTarget.FromMesh = function (mesh, name, influence) {
  79173. if (!name) {
  79174. name = mesh.name;
  79175. }
  79176. var result = new MorphTarget(name, influence);
  79177. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  79178. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  79179. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  79180. }
  79181. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  79182. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  79183. }
  79184. return result;
  79185. };
  79186. return MorphTarget;
  79187. }());
  79188. BABYLON.MorphTarget = MorphTarget;
  79189. })(BABYLON || (BABYLON = {}));
  79190. //# sourceMappingURL=babylon.morphTarget.js.map
  79191. var BABYLON;
  79192. (function (BABYLON) {
  79193. var MorphTargetManager = /** @class */ (function () {
  79194. function MorphTargetManager(scene) {
  79195. if (scene === void 0) { scene = null; }
  79196. this._targets = new Array();
  79197. this._targetObservable = new Array();
  79198. this._activeTargets = new BABYLON.SmartArray(16);
  79199. this._supportsNormals = false;
  79200. this._supportsTangents = false;
  79201. this._vertexCount = 0;
  79202. this._uniqueId = 0;
  79203. this._tempInfluences = new Array();
  79204. if (!scene) {
  79205. scene = BABYLON.Engine.LastCreatedScene;
  79206. }
  79207. this._scene = scene;
  79208. if (this._scene) {
  79209. this._scene.morphTargetManagers.push(this);
  79210. this._uniqueId = this._scene.getUniqueId();
  79211. }
  79212. }
  79213. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  79214. get: function () {
  79215. return this._uniqueId;
  79216. },
  79217. enumerable: true,
  79218. configurable: true
  79219. });
  79220. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  79221. get: function () {
  79222. return this._vertexCount;
  79223. },
  79224. enumerable: true,
  79225. configurable: true
  79226. });
  79227. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  79228. get: function () {
  79229. return this._supportsNormals;
  79230. },
  79231. enumerable: true,
  79232. configurable: true
  79233. });
  79234. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  79235. get: function () {
  79236. return this._supportsTangents;
  79237. },
  79238. enumerable: true,
  79239. configurable: true
  79240. });
  79241. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  79242. get: function () {
  79243. return this._targets.length;
  79244. },
  79245. enumerable: true,
  79246. configurable: true
  79247. });
  79248. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  79249. get: function () {
  79250. return this._activeTargets.length;
  79251. },
  79252. enumerable: true,
  79253. configurable: true
  79254. });
  79255. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  79256. get: function () {
  79257. return this._influences;
  79258. },
  79259. enumerable: true,
  79260. configurable: true
  79261. });
  79262. MorphTargetManager.prototype.getActiveTarget = function (index) {
  79263. return this._activeTargets.data[index];
  79264. };
  79265. MorphTargetManager.prototype.getTarget = function (index) {
  79266. return this._targets[index];
  79267. };
  79268. MorphTargetManager.prototype.addTarget = function (target) {
  79269. var _this = this;
  79270. this._targets.push(target);
  79271. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  79272. _this._syncActiveTargets(needUpdate);
  79273. }));
  79274. this._syncActiveTargets(true);
  79275. };
  79276. MorphTargetManager.prototype.removeTarget = function (target) {
  79277. var index = this._targets.indexOf(target);
  79278. if (index >= 0) {
  79279. this._targets.splice(index, 1);
  79280. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  79281. this._syncActiveTargets(true);
  79282. }
  79283. };
  79284. /**
  79285. * Serializes the current manager into a Serialization object.
  79286. * Returns the serialized object.
  79287. */
  79288. MorphTargetManager.prototype.serialize = function () {
  79289. var serializationObject = {};
  79290. serializationObject.id = this.uniqueId;
  79291. serializationObject.targets = [];
  79292. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79293. var target = _a[_i];
  79294. serializationObject.targets.push(target.serialize());
  79295. }
  79296. return serializationObject;
  79297. };
  79298. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  79299. var influenceCount = 0;
  79300. this._activeTargets.reset();
  79301. this._supportsNormals = true;
  79302. this._supportsTangents = true;
  79303. this._vertexCount = 0;
  79304. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  79305. var target = _a[_i];
  79306. this._activeTargets.push(target);
  79307. this._tempInfluences[influenceCount++] = target.influence;
  79308. var positions = target.getPositions();
  79309. if (positions) {
  79310. this._supportsNormals = this._supportsNormals && target.hasNormals;
  79311. this._supportsTangents = this._supportsTangents && target.hasTangents;
  79312. var vertexCount = positions.length / 3;
  79313. if (this._vertexCount === 0) {
  79314. this._vertexCount = vertexCount;
  79315. }
  79316. else if (this._vertexCount !== vertexCount) {
  79317. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  79318. return;
  79319. }
  79320. }
  79321. }
  79322. if (!this._influences || this._influences.length !== influenceCount) {
  79323. this._influences = new Float32Array(influenceCount);
  79324. }
  79325. for (var index = 0; index < influenceCount; index++) {
  79326. this._influences[index] = this._tempInfluences[index];
  79327. }
  79328. if (needUpdate && this._scene) {
  79329. // Flag meshes as dirty to resync with the active targets
  79330. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  79331. var mesh = _c[_b];
  79332. if (mesh.morphTargetManager === this) {
  79333. mesh._syncGeometryWithMorphTargetManager();
  79334. }
  79335. }
  79336. }
  79337. };
  79338. // Statics
  79339. MorphTargetManager.Parse = function (serializationObject, scene) {
  79340. var result = new MorphTargetManager(scene);
  79341. result._uniqueId = serializationObject.id;
  79342. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  79343. var targetData = _a[_i];
  79344. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  79345. }
  79346. return result;
  79347. };
  79348. return MorphTargetManager;
  79349. }());
  79350. BABYLON.MorphTargetManager = MorphTargetManager;
  79351. })(BABYLON || (BABYLON = {}));
  79352. //# sourceMappingURL=babylon.morphTargetManager.js.map
  79353. var BABYLON;
  79354. (function (BABYLON) {
  79355. var Octree = /** @class */ (function () {
  79356. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  79357. if (maxDepth === void 0) { maxDepth = 2; }
  79358. this.maxDepth = maxDepth;
  79359. this.dynamicContent = new Array();
  79360. this._maxBlockCapacity = maxBlockCapacity || 64;
  79361. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  79362. this._creationFunc = creationFunc;
  79363. }
  79364. // Methods
  79365. Octree.prototype.update = function (worldMin, worldMax, entries) {
  79366. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  79367. };
  79368. Octree.prototype.addMesh = function (entry) {
  79369. for (var index = 0; index < this.blocks.length; index++) {
  79370. var block = this.blocks[index];
  79371. block.addEntry(entry);
  79372. }
  79373. };
  79374. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  79375. this._selectionContent.reset();
  79376. for (var index = 0; index < this.blocks.length; index++) {
  79377. var block = this.blocks[index];
  79378. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  79379. }
  79380. if (allowDuplicate) {
  79381. this._selectionContent.concat(this.dynamicContent);
  79382. }
  79383. else {
  79384. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79385. }
  79386. return this._selectionContent;
  79387. };
  79388. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  79389. this._selectionContent.reset();
  79390. for (var index = 0; index < this.blocks.length; index++) {
  79391. var block = this.blocks[index];
  79392. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  79393. }
  79394. if (allowDuplicate) {
  79395. this._selectionContent.concat(this.dynamicContent);
  79396. }
  79397. else {
  79398. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79399. }
  79400. return this._selectionContent;
  79401. };
  79402. Octree.prototype.intersectsRay = function (ray) {
  79403. this._selectionContent.reset();
  79404. for (var index = 0; index < this.blocks.length; index++) {
  79405. var block = this.blocks[index];
  79406. block.intersectsRay(ray, this._selectionContent);
  79407. }
  79408. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  79409. return this._selectionContent;
  79410. };
  79411. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  79412. target.blocks = new Array();
  79413. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  79414. // Segmenting space
  79415. for (var x = 0; x < 2; x++) {
  79416. for (var y = 0; y < 2; y++) {
  79417. for (var z = 0; z < 2; z++) {
  79418. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  79419. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  79420. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  79421. block.addEntries(entries);
  79422. target.blocks.push(block);
  79423. }
  79424. }
  79425. }
  79426. };
  79427. Octree.CreationFuncForMeshes = function (entry, block) {
  79428. var boundingInfo = entry.getBoundingInfo();
  79429. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79430. block.entries.push(entry);
  79431. }
  79432. };
  79433. Octree.CreationFuncForSubMeshes = function (entry, block) {
  79434. var boundingInfo = entry.getBoundingInfo();
  79435. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  79436. block.entries.push(entry);
  79437. }
  79438. };
  79439. return Octree;
  79440. }());
  79441. BABYLON.Octree = Octree;
  79442. })(BABYLON || (BABYLON = {}));
  79443. //# sourceMappingURL=babylon.octree.js.map
  79444. var BABYLON;
  79445. (function (BABYLON) {
  79446. var OctreeBlock = /** @class */ (function () {
  79447. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  79448. this.entries = new Array();
  79449. this._boundingVectors = new Array();
  79450. this._capacity = capacity;
  79451. this._depth = depth;
  79452. this._maxDepth = maxDepth;
  79453. this._creationFunc = creationFunc;
  79454. this._minPoint = minPoint;
  79455. this._maxPoint = maxPoint;
  79456. this._boundingVectors.push(minPoint.clone());
  79457. this._boundingVectors.push(maxPoint.clone());
  79458. this._boundingVectors.push(minPoint.clone());
  79459. this._boundingVectors[2].x = maxPoint.x;
  79460. this._boundingVectors.push(minPoint.clone());
  79461. this._boundingVectors[3].y = maxPoint.y;
  79462. this._boundingVectors.push(minPoint.clone());
  79463. this._boundingVectors[4].z = maxPoint.z;
  79464. this._boundingVectors.push(maxPoint.clone());
  79465. this._boundingVectors[5].z = minPoint.z;
  79466. this._boundingVectors.push(maxPoint.clone());
  79467. this._boundingVectors[6].x = minPoint.x;
  79468. this._boundingVectors.push(maxPoint.clone());
  79469. this._boundingVectors[7].y = minPoint.y;
  79470. }
  79471. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  79472. // Property
  79473. get: function () {
  79474. return this._capacity;
  79475. },
  79476. enumerable: true,
  79477. configurable: true
  79478. });
  79479. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  79480. get: function () {
  79481. return this._minPoint;
  79482. },
  79483. enumerable: true,
  79484. configurable: true
  79485. });
  79486. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  79487. get: function () {
  79488. return this._maxPoint;
  79489. },
  79490. enumerable: true,
  79491. configurable: true
  79492. });
  79493. // Methods
  79494. OctreeBlock.prototype.addEntry = function (entry) {
  79495. if (this.blocks) {
  79496. for (var index = 0; index < this.blocks.length; index++) {
  79497. var block = this.blocks[index];
  79498. block.addEntry(entry);
  79499. }
  79500. return;
  79501. }
  79502. this._creationFunc(entry, this);
  79503. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  79504. this.createInnerBlocks();
  79505. }
  79506. };
  79507. OctreeBlock.prototype.addEntries = function (entries) {
  79508. for (var index = 0; index < entries.length; index++) {
  79509. var mesh = entries[index];
  79510. this.addEntry(mesh);
  79511. }
  79512. };
  79513. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  79514. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  79515. if (this.blocks) {
  79516. for (var index = 0; index < this.blocks.length; index++) {
  79517. var block = this.blocks[index];
  79518. block.select(frustumPlanes, selection, allowDuplicate);
  79519. }
  79520. return;
  79521. }
  79522. if (allowDuplicate) {
  79523. selection.concat(this.entries);
  79524. }
  79525. else {
  79526. selection.concatWithNoDuplicate(this.entries);
  79527. }
  79528. }
  79529. };
  79530. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  79531. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  79532. if (this.blocks) {
  79533. for (var index = 0; index < this.blocks.length; index++) {
  79534. var block = this.blocks[index];
  79535. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  79536. }
  79537. return;
  79538. }
  79539. if (allowDuplicate) {
  79540. selection.concat(this.entries);
  79541. }
  79542. else {
  79543. selection.concatWithNoDuplicate(this.entries);
  79544. }
  79545. }
  79546. };
  79547. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  79548. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  79549. if (this.blocks) {
  79550. for (var index = 0; index < this.blocks.length; index++) {
  79551. var block = this.blocks[index];
  79552. block.intersectsRay(ray, selection);
  79553. }
  79554. return;
  79555. }
  79556. selection.concatWithNoDuplicate(this.entries);
  79557. }
  79558. };
  79559. OctreeBlock.prototype.createInnerBlocks = function () {
  79560. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  79561. };
  79562. return OctreeBlock;
  79563. }());
  79564. BABYLON.OctreeBlock = OctreeBlock;
  79565. })(BABYLON || (BABYLON = {}));
  79566. //# sourceMappingURL=babylon.octreeBlock.js.map
  79567. var BABYLON;
  79568. (function (BABYLON) {
  79569. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  79570. __extends(VRDistortionCorrectionPostProcess, _super);
  79571. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  79572. var _this = _super.call(this, name, "vrDistortionCorrection", [
  79573. 'LensCenter',
  79574. 'Scale',
  79575. 'ScaleIn',
  79576. 'HmdWarpParam'
  79577. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  79578. _this._isRightEye = isRightEye;
  79579. _this._distortionFactors = vrMetrics.distortionK;
  79580. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  79581. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  79582. _this.adaptScaleToCurrentViewport = true;
  79583. _this.onSizeChangedObservable.add(function () {
  79584. _this.aspectRatio = _this.width * .5 / _this.height;
  79585. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  79586. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  79587. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  79588. });
  79589. _this.onApplyObservable.add(function (effect) {
  79590. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  79591. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  79592. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  79593. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  79594. });
  79595. return _this;
  79596. }
  79597. return VRDistortionCorrectionPostProcess;
  79598. }(BABYLON.PostProcess));
  79599. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  79600. })(BABYLON || (BABYLON = {}));
  79601. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  79602. var BABYLON;
  79603. (function (BABYLON) {
  79604. var AnaglyphPostProcess = /** @class */ (function (_super) {
  79605. __extends(AnaglyphPostProcess, _super);
  79606. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  79607. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  79608. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79609. _this.onApplyObservable.add(function (effect) {
  79610. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  79611. });
  79612. return _this;
  79613. }
  79614. return AnaglyphPostProcess;
  79615. }(BABYLON.PostProcess));
  79616. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  79617. })(BABYLON || (BABYLON = {}));
  79618. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  79619. var BABYLON;
  79620. (function (BABYLON) {
  79621. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  79622. __extends(StereoscopicInterlacePostProcess, _super);
  79623. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  79624. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  79625. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79626. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79627. _this.onSizeChangedObservable.add(function () {
  79628. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79629. });
  79630. _this.onApplyObservable.add(function (effect) {
  79631. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  79632. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  79633. });
  79634. return _this;
  79635. }
  79636. return StereoscopicInterlacePostProcess;
  79637. }(BABYLON.PostProcess));
  79638. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  79639. })(BABYLON || (BABYLON = {}));
  79640. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  79641. var BABYLON;
  79642. (function (BABYLON) {
  79643. /**
  79644. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  79645. * Screen rotation is taken into account.
  79646. */
  79647. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  79648. function FreeCameraDeviceOrientationInput() {
  79649. var _this = this;
  79650. this._screenOrientationAngle = 0;
  79651. this._screenQuaternion = new BABYLON.Quaternion();
  79652. this._alpha = 0;
  79653. this._beta = 0;
  79654. this._gamma = 0;
  79655. this._orientationChanged = function () {
  79656. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  79657. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  79658. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  79659. };
  79660. this._deviceOrientation = function (evt) {
  79661. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  79662. _this._beta = evt.beta !== null ? evt.beta : 0;
  79663. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  79664. };
  79665. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  79666. this._orientationChanged();
  79667. }
  79668. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  79669. get: function () {
  79670. return this._camera;
  79671. },
  79672. set: function (camera) {
  79673. this._camera = camera;
  79674. if (this._camera != null && !this._camera.rotationQuaternion) {
  79675. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  79676. }
  79677. },
  79678. enumerable: true,
  79679. configurable: true
  79680. });
  79681. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79682. window.addEventListener("orientationchange", this._orientationChanged);
  79683. window.addEventListener("deviceorientation", this._deviceOrientation);
  79684. //In certain cases, the attach control is called AFTER orientation was changed,
  79685. //So this is needed.
  79686. this._orientationChanged();
  79687. };
  79688. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  79689. window.removeEventListener("orientationchange", this._orientationChanged);
  79690. window.removeEventListener("deviceorientation", this._deviceOrientation);
  79691. };
  79692. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  79693. //if no device orientation provided, don't update the rotation.
  79694. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  79695. if (!this._alpha)
  79696. return;
  79697. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  79698. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  79699. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  79700. //Mirror on XY Plane
  79701. this._camera.rotationQuaternion.z *= -1;
  79702. this._camera.rotationQuaternion.w *= -1;
  79703. };
  79704. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  79705. return "FreeCameraDeviceOrientationInput";
  79706. };
  79707. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  79708. return "deviceOrientation";
  79709. };
  79710. return FreeCameraDeviceOrientationInput;
  79711. }());
  79712. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  79713. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  79714. })(BABYLON || (BABYLON = {}));
  79715. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  79716. var BABYLON;
  79717. (function (BABYLON) {
  79718. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  79719. function ArcRotateCameraVRDeviceOrientationInput() {
  79720. this.alphaCorrection = 1;
  79721. this.betaCorrection = 1;
  79722. this.gammaCorrection = 1;
  79723. this._alpha = 0;
  79724. this._gamma = 0;
  79725. this._dirty = false;
  79726. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  79727. }
  79728. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79729. this.camera.attachControl(element, noPreventDefault);
  79730. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  79731. };
  79732. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  79733. if (evt.alpha !== null) {
  79734. this._alpha = +evt.alpha | 0;
  79735. }
  79736. if (evt.gamma !== null) {
  79737. this._gamma = +evt.gamma | 0;
  79738. }
  79739. this._dirty = true;
  79740. };
  79741. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  79742. if (this._dirty) {
  79743. this._dirty = false;
  79744. if (this._gamma < 0) {
  79745. this._gamma = 180 + this._gamma;
  79746. }
  79747. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  79748. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  79749. }
  79750. };
  79751. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  79752. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  79753. };
  79754. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  79755. return "ArcRotateCameraVRDeviceOrientationInput";
  79756. };
  79757. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  79758. return "VRDeviceOrientation";
  79759. };
  79760. return ArcRotateCameraVRDeviceOrientationInput;
  79761. }());
  79762. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  79763. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  79764. })(BABYLON || (BABYLON = {}));
  79765. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  79766. var BABYLON;
  79767. (function (BABYLON) {
  79768. var VRCameraMetrics = /** @class */ (function () {
  79769. function VRCameraMetrics() {
  79770. this.compensateDistortion = true;
  79771. }
  79772. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  79773. get: function () {
  79774. return this.hResolution / (2 * this.vResolution);
  79775. },
  79776. enumerable: true,
  79777. configurable: true
  79778. });
  79779. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  79780. get: function () {
  79781. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  79782. },
  79783. enumerable: true,
  79784. configurable: true
  79785. });
  79786. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  79787. get: function () {
  79788. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79789. var h = (4 * meters) / this.hScreenSize;
  79790. return BABYLON.Matrix.Translation(h, 0, 0);
  79791. },
  79792. enumerable: true,
  79793. configurable: true
  79794. });
  79795. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  79796. get: function () {
  79797. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79798. var h = (4 * meters) / this.hScreenSize;
  79799. return BABYLON.Matrix.Translation(-h, 0, 0);
  79800. },
  79801. enumerable: true,
  79802. configurable: true
  79803. });
  79804. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  79805. get: function () {
  79806. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  79807. },
  79808. enumerable: true,
  79809. configurable: true
  79810. });
  79811. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  79812. get: function () {
  79813. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  79814. },
  79815. enumerable: true,
  79816. configurable: true
  79817. });
  79818. VRCameraMetrics.GetDefault = function () {
  79819. var result = new VRCameraMetrics();
  79820. result.hResolution = 1280;
  79821. result.vResolution = 800;
  79822. result.hScreenSize = 0.149759993;
  79823. result.vScreenSize = 0.0935999975;
  79824. result.vScreenCenter = 0.0467999987;
  79825. result.eyeToScreenDistance = 0.0410000011;
  79826. result.lensSeparationDistance = 0.0635000020;
  79827. result.interpupillaryDistance = 0.0640000030;
  79828. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  79829. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  79830. result.postProcessScaleFactor = 1.714605507808412;
  79831. result.lensCenterOffset = 0.151976421;
  79832. return result;
  79833. };
  79834. return VRCameraMetrics;
  79835. }());
  79836. BABYLON.VRCameraMetrics = VRCameraMetrics;
  79837. })(BABYLON || (BABYLON = {}));
  79838. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  79839. var BABYLON;
  79840. (function (BABYLON) {
  79841. /**
  79842. * This represents a WebVR camera.
  79843. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  79844. * @example http://doc.babylonjs.com/how_to/webvr_camera
  79845. */
  79846. var WebVRFreeCamera = /** @class */ (function (_super) {
  79847. __extends(WebVRFreeCamera, _super);
  79848. /**
  79849. * Instantiates a WebVRFreeCamera.
  79850. * @param name The name of the WebVRFreeCamera
  79851. * @param position The starting anchor position for the camera
  79852. * @param scene The scene the camera belongs to
  79853. * @param webVROptions a set of customizable options for the webVRCamera
  79854. */
  79855. function WebVRFreeCamera(name, position, scene, webVROptions) {
  79856. if (webVROptions === void 0) { webVROptions = {}; }
  79857. var _this = _super.call(this, name, position, scene) || this;
  79858. _this.webVROptions = webVROptions;
  79859. /**
  79860. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  79861. */
  79862. _this._vrDevice = null;
  79863. /**
  79864. * The rawPose of the vrDevice.
  79865. */
  79866. _this.rawPose = null;
  79867. _this._specsVersion = "1.1";
  79868. _this._attached = false;
  79869. _this._descendants = [];
  79870. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79871. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  79872. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  79873. _this._standingMatrix = null;
  79874. /**
  79875. * Represents device position in babylon space.
  79876. */
  79877. _this.devicePosition = BABYLON.Vector3.Zero();
  79878. /**
  79879. * Represents device rotation in babylon space.
  79880. */
  79881. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  79882. /**
  79883. * The scale of the device to be used when translating from device space to babylon space.
  79884. */
  79885. _this.deviceScaleFactor = 1;
  79886. _this._deviceToWorld = BABYLON.Matrix.Identity();
  79887. _this._worldToDevice = BABYLON.Matrix.Identity();
  79888. /**
  79889. * References to the webVR controllers for the vrDevice.
  79890. */
  79891. _this.controllers = [];
  79892. /**
  79893. * Emits an event when a controller is attached.
  79894. */
  79895. _this.onControllersAttachedObservable = new BABYLON.Observable();
  79896. /**
  79897. * Emits an event when a controller's mesh has been loaded;
  79898. */
  79899. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79900. /**
  79901. * If the rig cameras be used as parent instead of this camera.
  79902. */
  79903. _this.rigParenting = true;
  79904. _this._defaultHeight = undefined;
  79905. _this._workingVector = BABYLON.Vector3.Zero();
  79906. _this._oneVector = BABYLON.Vector3.One();
  79907. _this._workingMatrix = BABYLON.Matrix.Identity();
  79908. _this._cache.position = BABYLON.Vector3.Zero();
  79909. if (webVROptions.defaultHeight) {
  79910. _this._defaultHeight = webVROptions.defaultHeight;
  79911. _this.position.y = _this._defaultHeight;
  79912. }
  79913. _this.minZ = 0.1;
  79914. //legacy support - the compensation boolean was removed.
  79915. if (arguments.length === 5) {
  79916. _this.webVROptions = arguments[4];
  79917. }
  79918. // default webVR options
  79919. if (_this.webVROptions.trackPosition == undefined) {
  79920. _this.webVROptions.trackPosition = true;
  79921. }
  79922. if (_this.webVROptions.controllerMeshes == undefined) {
  79923. _this.webVROptions.controllerMeshes = true;
  79924. }
  79925. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  79926. _this.webVROptions.defaultLightingOnControllers = true;
  79927. }
  79928. _this.rotationQuaternion = new BABYLON.Quaternion();
  79929. if (_this.webVROptions && _this.webVROptions.positionScale) {
  79930. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  79931. }
  79932. //enable VR
  79933. var engine = _this.getEngine();
  79934. _this._onVREnabled = function (success) { if (success) {
  79935. _this.initControllers();
  79936. } };
  79937. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  79938. engine.initWebVR().add(function (event) {
  79939. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  79940. return;
  79941. }
  79942. _this._vrDevice = event.vrDisplay;
  79943. //reset the rig parameters.
  79944. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  79945. if (_this._attached) {
  79946. _this.getEngine().enableVR();
  79947. }
  79948. });
  79949. if (typeof (VRFrameData) !== "undefined")
  79950. _this._frameData = new VRFrameData();
  79951. /**
  79952. * The idea behind the following lines:
  79953. * objects that have the camera as parent should actually have the rig cameras as a parent.
  79954. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  79955. * the second will not show it correctly.
  79956. *
  79957. * To solve this - each object that has the camera as parent will be added to a protected array.
  79958. * When the rig camera renders, it will take this array and set all of those to be its children.
  79959. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  79960. * Amazing!
  79961. */
  79962. scene.onBeforeCameraRenderObservable.add(function (camera) {
  79963. if (camera.parent === _this && _this.rigParenting) {
  79964. _this._descendants = _this.getDescendants(true, function (n) {
  79965. // don't take the cameras or the controllers!
  79966. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  79967. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  79968. return !isController && !isRigCamera;
  79969. });
  79970. _this._descendants.forEach(function (node) {
  79971. node.parent = camera;
  79972. });
  79973. }
  79974. });
  79975. scene.onAfterCameraRenderObservable.add(function (camera) {
  79976. if (camera.parent === _this && _this.rigParenting) {
  79977. _this._descendants.forEach(function (node) {
  79978. node.parent = _this;
  79979. });
  79980. }
  79981. });
  79982. return _this;
  79983. }
  79984. /**
  79985. * Gets the device distance from the ground in meters.
  79986. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  79987. */
  79988. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  79989. if (this._standingMatrix) {
  79990. // Add standing matrix offset to get real offset from ground in room
  79991. this._standingMatrix.getTranslationToRef(this._workingVector);
  79992. return this._deviceRoomPosition.y + this._workingVector.y;
  79993. }
  79994. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  79995. return this._defaultHeight || 0;
  79996. };
  79997. /**
  79998. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79999. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  80000. */
  80001. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  80002. var _this = this;
  80003. if (callback === void 0) { callback = function (bool) { }; }
  80004. // Use standing matrix if available
  80005. this.getEngine().initWebVRAsync().then(function (result) {
  80006. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  80007. callback(false);
  80008. }
  80009. else {
  80010. _this._standingMatrix = new BABYLON.Matrix();
  80011. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  80012. if (!_this.getScene().useRightHandedSystem) {
  80013. [2, 6, 8, 9, 14].forEach(function (num) {
  80014. if (_this._standingMatrix) {
  80015. _this._standingMatrix.m[num] *= -1;
  80016. }
  80017. });
  80018. }
  80019. callback(true);
  80020. }
  80021. });
  80022. };
  80023. /**
  80024. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80025. * @returns A promise with a boolean set to if the standing matrix is supported.
  80026. */
  80027. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  80028. var _this = this;
  80029. return new Promise(function (res, rej) {
  80030. _this.useStandingMatrix(function (supported) {
  80031. res(supported);
  80032. });
  80033. });
  80034. };
  80035. /**
  80036. * Disposes the camera
  80037. */
  80038. WebVRFreeCamera.prototype.dispose = function () {
  80039. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  80040. _super.prototype.dispose.call(this);
  80041. };
  80042. /**
  80043. * Gets a vrController by name.
  80044. * @param name The name of the controller to retreive
  80045. * @returns the controller matching the name specified or null if not found
  80046. */
  80047. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  80048. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  80049. var gp = _a[_i];
  80050. if (gp.hand === name) {
  80051. return gp;
  80052. }
  80053. }
  80054. return null;
  80055. };
  80056. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  80057. /**
  80058. * The controller corrisponding to the users left hand.
  80059. */
  80060. get: function () {
  80061. if (!this._leftController) {
  80062. this._leftController = this.getControllerByName("left");
  80063. }
  80064. return this._leftController;
  80065. },
  80066. enumerable: true,
  80067. configurable: true
  80068. });
  80069. ;
  80070. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  80071. /**
  80072. * The controller corrisponding to the users right hand.
  80073. */
  80074. get: function () {
  80075. if (!this._rightController) {
  80076. this._rightController = this.getControllerByName("right");
  80077. }
  80078. return this._rightController;
  80079. },
  80080. enumerable: true,
  80081. configurable: true
  80082. });
  80083. ;
  80084. /**
  80085. * Casts a ray forward from the vrCamera's gaze.
  80086. * @param length Length of the ray (default: 100)
  80087. * @returns the ray corrisponding to the gaze
  80088. */
  80089. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  80090. if (length === void 0) { length = 100; }
  80091. if (this.leftCamera) {
  80092. // Use left eye to avoid computation to compute center on every call
  80093. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  80094. }
  80095. else {
  80096. return _super.prototype.getForwardRay.call(this, length);
  80097. }
  80098. };
  80099. /**
  80100. * Updates the camera based on device's frame data
  80101. */
  80102. WebVRFreeCamera.prototype._checkInputs = function () {
  80103. if (this._vrDevice && this._vrDevice.isPresenting) {
  80104. this._vrDevice.getFrameData(this._frameData);
  80105. this.updateFromDevice(this._frameData.pose);
  80106. }
  80107. _super.prototype._checkInputs.call(this);
  80108. };
  80109. /**
  80110. * Updates the poseControlled values based on the input device pose.
  80111. * @param poseData Pose coming from the device
  80112. */
  80113. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  80114. if (poseData && poseData.orientation) {
  80115. this.rawPose = poseData;
  80116. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  80117. if (this.getScene().useRightHandedSystem) {
  80118. this._deviceRoomRotationQuaternion.z *= -1;
  80119. this._deviceRoomRotationQuaternion.w *= -1;
  80120. }
  80121. if (this.webVROptions.trackPosition && this.rawPose.position) {
  80122. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  80123. if (this.getScene().useRightHandedSystem) {
  80124. this._deviceRoomPosition.z *= -1;
  80125. }
  80126. }
  80127. }
  80128. };
  80129. /**
  80130. * WebVR's attach control will start broadcasting frames to the device.
  80131. * Note that in certain browsers (chrome for example) this function must be called
  80132. * within a user-interaction callback. Example:
  80133. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  80134. *
  80135. * @param element html element to attach the vrDevice to
  80136. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  80137. */
  80138. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  80139. _super.prototype.attachControl.call(this, element, noPreventDefault);
  80140. this._attached = true;
  80141. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  80142. if (this._vrDevice) {
  80143. this.getEngine().enableVR();
  80144. }
  80145. };
  80146. /**
  80147. * Detaches the camera from the html element and disables VR
  80148. *
  80149. * @param element html element to detach from
  80150. */
  80151. WebVRFreeCamera.prototype.detachControl = function (element) {
  80152. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  80153. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  80154. _super.prototype.detachControl.call(this, element);
  80155. this._attached = false;
  80156. this.getEngine().disableVR();
  80157. };
  80158. /**
  80159. * @returns the name of this class
  80160. */
  80161. WebVRFreeCamera.prototype.getClassName = function () {
  80162. return "WebVRFreeCamera";
  80163. };
  80164. /**
  80165. * Calls resetPose on the vrDisplay
  80166. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  80167. */
  80168. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  80169. //uses the vrDisplay's "resetPose()".
  80170. //pitch and roll won't be affected.
  80171. this._vrDevice.resetPose();
  80172. };
  80173. /**
  80174. * Updates the rig cameras (left and right eye)
  80175. */
  80176. WebVRFreeCamera.prototype._updateRigCameras = function () {
  80177. var camLeft = this._rigCameras[0];
  80178. var camRight = this._rigCameras[1];
  80179. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80180. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80181. camLeft.position.copyFrom(this._deviceRoomPosition);
  80182. camRight.position.copyFrom(this._deviceRoomPosition);
  80183. };
  80184. /**
  80185. * Updates the cached values of the camera
  80186. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  80187. */
  80188. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  80189. var _this = this;
  80190. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  80191. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  80192. if (!this.updateCacheCalled) {
  80193. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  80194. this.updateCacheCalled = true;
  80195. this.update();
  80196. }
  80197. // Set working vector to the device position in room space rotated by the new rotation
  80198. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  80199. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  80200. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  80201. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  80202. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  80203. // Add translation from anchor position
  80204. this._deviceToWorld.getTranslationToRef(this._workingVector);
  80205. this._workingVector.addInPlace(this.position);
  80206. this._workingVector.subtractInPlace(this._cache.position);
  80207. this._deviceToWorld.setTranslation(this._workingVector);
  80208. // Set an inverted matrix to be used when updating the camera
  80209. this._deviceToWorld.invertToRef(this._worldToDevice);
  80210. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  80211. this.controllers.forEach(function (controller) {
  80212. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  80213. controller.update();
  80214. });
  80215. }
  80216. if (!ignoreParentClass) {
  80217. _super.prototype._updateCache.call(this);
  80218. }
  80219. this.updateCacheCalled = false;
  80220. };
  80221. /**
  80222. * Updates the current device position and rotation in the babylon world
  80223. */
  80224. WebVRFreeCamera.prototype.update = function () {
  80225. // Get current device position in babylon world
  80226. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  80227. // Get current device rotation in babylon world
  80228. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  80229. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  80230. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  80231. _super.prototype.update.call(this);
  80232. };
  80233. /**
  80234. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  80235. * @returns an identity matrix
  80236. */
  80237. WebVRFreeCamera.prototype._getViewMatrix = function () {
  80238. return BABYLON.Matrix.Identity();
  80239. };
  80240. /**
  80241. * This function is called by the two RIG cameras.
  80242. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  80243. */
  80244. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  80245. var _this = this;
  80246. // Update the parent camera prior to using a child camera to avoid desynchronization
  80247. var parentCamera = this._cameraRigParams["parentCamera"];
  80248. parentCamera._updateCache();
  80249. //WebVR 1.1
  80250. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  80251. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  80252. if (!this.getScene().useRightHandedSystem) {
  80253. [2, 6, 8, 9, 14].forEach(function (num) {
  80254. _this._webvrViewMatrix.m[num] *= -1;
  80255. });
  80256. }
  80257. // update the camera rotation matrix
  80258. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  80259. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  80260. // Computing target and final matrix
  80261. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  80262. // should the view matrix be updated with scale and position offset?
  80263. if (parentCamera.deviceScaleFactor !== 1) {
  80264. this._webvrViewMatrix.invert();
  80265. // scale the position, if set
  80266. if (parentCamera.deviceScaleFactor) {
  80267. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  80268. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  80269. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  80270. }
  80271. this._webvrViewMatrix.invert();
  80272. }
  80273. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  80274. return this._webvrViewMatrix;
  80275. };
  80276. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  80277. var _this = this;
  80278. var parentCamera = this.parent;
  80279. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  80280. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  80281. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  80282. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  80283. //babylon compatible matrix
  80284. if (!this.getScene().useRightHandedSystem) {
  80285. [8, 9, 10, 11].forEach(function (num) {
  80286. _this._projectionMatrix.m[num] *= -1;
  80287. });
  80288. }
  80289. return this._projectionMatrix;
  80290. };
  80291. /**
  80292. * Initializes the controllers and their meshes
  80293. */
  80294. WebVRFreeCamera.prototype.initControllers = function () {
  80295. var _this = this;
  80296. this.controllers = [];
  80297. var manager = this.getScene().gamepadManager;
  80298. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  80299. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80300. var webVrController = gamepad;
  80301. if (webVrController.defaultModel) {
  80302. webVrController.defaultModel.setEnabled(false);
  80303. }
  80304. if (webVrController.hand === "right") {
  80305. _this._rightController = null;
  80306. }
  80307. if (webVrController.hand === "left") {
  80308. _this._leftController = null;
  80309. }
  80310. var controllerIndex = _this.controllers.indexOf(webVrController);
  80311. if (controllerIndex !== -1) {
  80312. _this.controllers.splice(controllerIndex, 1);
  80313. }
  80314. }
  80315. });
  80316. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  80317. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  80318. var webVrController_1 = gamepad;
  80319. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  80320. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  80321. if (_this.webVROptions.controllerMeshes) {
  80322. if (webVrController_1.defaultModel) {
  80323. webVrController_1.defaultModel.setEnabled(true);
  80324. }
  80325. else {
  80326. // Load the meshes
  80327. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  80328. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  80329. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  80330. if (_this.webVROptions.defaultLightingOnControllers) {
  80331. if (!_this._lightOnControllers) {
  80332. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  80333. }
  80334. var activateLightOnSubMeshes_1 = function (mesh, light) {
  80335. var children = mesh.getChildren();
  80336. if (children.length !== 0) {
  80337. children.forEach(function (mesh) {
  80338. light.includedOnlyMeshes.push(mesh);
  80339. activateLightOnSubMeshes_1(mesh, light);
  80340. });
  80341. }
  80342. };
  80343. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  80344. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  80345. }
  80346. });
  80347. }
  80348. }
  80349. webVrController_1.attachToPoseControlledCamera(_this);
  80350. // since this is async - sanity check. Is the controller already stored?
  80351. if (_this.controllers.indexOf(webVrController_1) === -1) {
  80352. //add to the controllers array
  80353. _this.controllers.push(webVrController_1);
  80354. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  80355. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  80356. // So we're overriding setting left & right manually to be sure
  80357. var firstViveWandDetected = false;
  80358. for (var i = 0; i < _this.controllers.length; i++) {
  80359. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  80360. if (!firstViveWandDetected) {
  80361. firstViveWandDetected = true;
  80362. _this.controllers[i].hand = "left";
  80363. }
  80364. else {
  80365. _this.controllers[i].hand = "right";
  80366. }
  80367. }
  80368. }
  80369. //did we find enough controllers? Great! let the developer know.
  80370. if (_this.controllers.length >= 2) {
  80371. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  80372. }
  80373. }
  80374. }
  80375. });
  80376. };
  80377. return WebVRFreeCamera;
  80378. }(BABYLON.FreeCamera));
  80379. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  80380. })(BABYLON || (BABYLON = {}));
  80381. //# sourceMappingURL=babylon.webVRCamera.js.map
  80382. var BABYLON;
  80383. (function (BABYLON) {
  80384. // We're mainly based on the logic defined into the FreeCamera code
  80385. /**
  80386. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  80387. * being tilted forward or back and left or right.
  80388. */
  80389. var DeviceOrientationCamera = /** @class */ (function (_super) {
  80390. __extends(DeviceOrientationCamera, _super);
  80391. /**
  80392. * Creates a new device orientation camera. @see DeviceOrientationCamera
  80393. * @param name The name of the camera
  80394. * @param position The start position camera
  80395. * @param scene The scene the camera belongs to
  80396. */
  80397. function DeviceOrientationCamera(name, position, scene) {
  80398. var _this = _super.call(this, name, position, scene) || this;
  80399. _this._quaternionCache = new BABYLON.Quaternion();
  80400. _this.inputs.addDeviceOrientation();
  80401. return _this;
  80402. }
  80403. /**
  80404. * Gets the current instance class name ("DeviceOrientationCamera").
  80405. * This helps avoiding instanceof at run time.
  80406. * @returns the class name
  80407. */
  80408. DeviceOrientationCamera.prototype.getClassName = function () {
  80409. return "DeviceOrientationCamera";
  80410. };
  80411. /**
  80412. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  80413. */
  80414. DeviceOrientationCamera.prototype._checkInputs = function () {
  80415. _super.prototype._checkInputs.call(this);
  80416. this._quaternionCache.copyFrom(this.rotationQuaternion);
  80417. if (this._initialQuaternion) {
  80418. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80419. }
  80420. };
  80421. /**
  80422. * Reset the camera to its default orientation on the specified axis only.
  80423. * @param axis The axis to reset
  80424. */
  80425. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  80426. var _this = this;
  80427. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  80428. //can only work if this camera has a rotation quaternion already.
  80429. if (!this.rotationQuaternion)
  80430. return;
  80431. if (!this._initialQuaternion) {
  80432. this._initialQuaternion = new BABYLON.Quaternion();
  80433. }
  80434. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  80435. ['x', 'y', 'z'].forEach(function (axisName) {
  80436. if (!axis[axisName]) {
  80437. _this._initialQuaternion[axisName] = 0;
  80438. }
  80439. else {
  80440. _this._initialQuaternion[axisName] *= -1;
  80441. }
  80442. });
  80443. this._initialQuaternion.normalize();
  80444. //force rotation update
  80445. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  80446. };
  80447. return DeviceOrientationCamera;
  80448. }(BABYLON.FreeCamera));
  80449. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  80450. })(BABYLON || (BABYLON = {}));
  80451. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  80452. var BABYLON;
  80453. (function (BABYLON) {
  80454. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  80455. __extends(VRDeviceOrientationFreeCamera, _super);
  80456. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80457. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80458. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80459. var _this = _super.call(this, name, position, scene) || this;
  80460. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80461. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80462. return _this;
  80463. }
  80464. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  80465. return "VRDeviceOrientationFreeCamera";
  80466. };
  80467. return VRDeviceOrientationFreeCamera;
  80468. }(BABYLON.DeviceOrientationCamera));
  80469. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  80470. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  80471. __extends(VRDeviceOrientationGamepadCamera, _super);
  80472. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  80473. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80474. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80475. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  80476. _this.inputs.addGamepad();
  80477. return _this;
  80478. }
  80479. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  80480. return "VRDeviceOrientationGamepadCamera";
  80481. };
  80482. return VRDeviceOrientationGamepadCamera;
  80483. }(VRDeviceOrientationFreeCamera));
  80484. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  80485. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  80486. __extends(VRDeviceOrientationArcRotateCamera, _super);
  80487. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  80488. if (compensateDistortion === void 0) { compensateDistortion = true; }
  80489. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  80490. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80491. vrCameraMetrics.compensateDistortion = compensateDistortion;
  80492. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  80493. _this.inputs.addVRDeviceOrientation();
  80494. return _this;
  80495. }
  80496. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  80497. return "VRDeviceOrientationArcRotateCamera";
  80498. };
  80499. return VRDeviceOrientationArcRotateCamera;
  80500. }(BABYLON.ArcRotateCamera));
  80501. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  80502. })(BABYLON || (BABYLON = {}));
  80503. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  80504. var BABYLON;
  80505. (function (BABYLON) {
  80506. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  80507. __extends(AnaglyphFreeCamera, _super);
  80508. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  80509. var _this = _super.call(this, name, position, scene) || this;
  80510. _this.interaxialDistance = interaxialDistance;
  80511. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80512. return _this;
  80513. }
  80514. AnaglyphFreeCamera.prototype.getClassName = function () {
  80515. return "AnaglyphFreeCamera";
  80516. };
  80517. return AnaglyphFreeCamera;
  80518. }(BABYLON.FreeCamera));
  80519. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  80520. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  80521. __extends(AnaglyphArcRotateCamera, _super);
  80522. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  80523. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80524. _this.interaxialDistance = interaxialDistance;
  80525. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80526. return _this;
  80527. }
  80528. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  80529. return "AnaglyphArcRotateCamera";
  80530. };
  80531. return AnaglyphArcRotateCamera;
  80532. }(BABYLON.ArcRotateCamera));
  80533. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  80534. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  80535. __extends(AnaglyphGamepadCamera, _super);
  80536. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  80537. var _this = _super.call(this, name, position, scene) || this;
  80538. _this.interaxialDistance = interaxialDistance;
  80539. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80540. return _this;
  80541. }
  80542. AnaglyphGamepadCamera.prototype.getClassName = function () {
  80543. return "AnaglyphGamepadCamera";
  80544. };
  80545. return AnaglyphGamepadCamera;
  80546. }(BABYLON.GamepadCamera));
  80547. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  80548. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  80549. __extends(AnaglyphUniversalCamera, _super);
  80550. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  80551. var _this = _super.call(this, name, position, scene) || this;
  80552. _this.interaxialDistance = interaxialDistance;
  80553. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80554. return _this;
  80555. }
  80556. AnaglyphUniversalCamera.prototype.getClassName = function () {
  80557. return "AnaglyphUniversalCamera";
  80558. };
  80559. return AnaglyphUniversalCamera;
  80560. }(BABYLON.UniversalCamera));
  80561. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  80562. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  80563. __extends(StereoscopicFreeCamera, _super);
  80564. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80565. var _this = _super.call(this, name, position, scene) || this;
  80566. _this.interaxialDistance = interaxialDistance;
  80567. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80568. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80569. return _this;
  80570. }
  80571. StereoscopicFreeCamera.prototype.getClassName = function () {
  80572. return "StereoscopicFreeCamera";
  80573. };
  80574. return StereoscopicFreeCamera;
  80575. }(BABYLON.FreeCamera));
  80576. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  80577. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  80578. __extends(StereoscopicArcRotateCamera, _super);
  80579. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  80580. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80581. _this.interaxialDistance = interaxialDistance;
  80582. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80583. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80584. return _this;
  80585. }
  80586. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  80587. return "StereoscopicArcRotateCamera";
  80588. };
  80589. return StereoscopicArcRotateCamera;
  80590. }(BABYLON.ArcRotateCamera));
  80591. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  80592. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  80593. __extends(StereoscopicGamepadCamera, _super);
  80594. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80595. var _this = _super.call(this, name, position, scene) || this;
  80596. _this.interaxialDistance = interaxialDistance;
  80597. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80598. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80599. return _this;
  80600. }
  80601. StereoscopicGamepadCamera.prototype.getClassName = function () {
  80602. return "StereoscopicGamepadCamera";
  80603. };
  80604. return StereoscopicGamepadCamera;
  80605. }(BABYLON.GamepadCamera));
  80606. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  80607. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  80608. __extends(StereoscopicUniversalCamera, _super);
  80609. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80610. var _this = _super.call(this, name, position, scene) || this;
  80611. _this.interaxialDistance = interaxialDistance;
  80612. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80613. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80614. return _this;
  80615. }
  80616. StereoscopicUniversalCamera.prototype.getClassName = function () {
  80617. return "StereoscopicUniversalCamera";
  80618. };
  80619. return StereoscopicUniversalCamera;
  80620. }(BABYLON.UniversalCamera));
  80621. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  80622. })(BABYLON || (BABYLON = {}));
  80623. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  80624. var BABYLON;
  80625. (function (BABYLON) {
  80626. var VRExperienceHelperGazer = /** @class */ (function () {
  80627. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  80628. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  80629. this.scene = scene;
  80630. this._pointerDownOnMeshAsked = false;
  80631. this._isActionableMesh = false;
  80632. this._teleportationRequestInitiated = false;
  80633. this._teleportationBackRequestInitiated = false;
  80634. this._dpadPressed = true;
  80635. this._activePointer = false;
  80636. this._id = VRExperienceHelperGazer._idCounter++;
  80637. // Gaze tracker
  80638. if (!gazeTrackerToClone) {
  80639. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  80640. this._gazeTracker.bakeCurrentTransformIntoVertices();
  80641. this._gazeTracker.isPickable = false;
  80642. this._gazeTracker.isVisible = false;
  80643. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  80644. targetMat.specularColor = BABYLON.Color3.Black();
  80645. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80646. targetMat.backFaceCulling = false;
  80647. this._gazeTracker.material = targetMat;
  80648. }
  80649. else {
  80650. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  80651. }
  80652. }
  80653. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  80654. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  80655. };
  80656. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  80657. this._pointerDownOnMeshAsked = true;
  80658. if (this._currentMeshSelected && this._currentHit) {
  80659. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  80660. }
  80661. };
  80662. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  80663. if (this._currentMeshSelected && this._currentHit) {
  80664. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  80665. }
  80666. this._pointerDownOnMeshAsked = false;
  80667. };
  80668. VRExperienceHelperGazer.prototype._activatePointer = function () {
  80669. this._activePointer = true;
  80670. };
  80671. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  80672. this._activePointer = false;
  80673. };
  80674. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  80675. };
  80676. VRExperienceHelperGazer.prototype.dispose = function () {
  80677. this._interactionsEnabled = false;
  80678. this._teleportationEnabled = false;
  80679. };
  80680. VRExperienceHelperGazer._idCounter = 0;
  80681. return VRExperienceHelperGazer;
  80682. }());
  80683. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  80684. __extends(VRExperienceHelperControllerGazer, _super);
  80685. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  80686. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  80687. _this.webVRController = webVRController;
  80688. // Laser pointer
  80689. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  80690. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  80691. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80692. laserPointerMaterial.alpha = 0.6;
  80693. _this._laserPointer.material = laserPointerMaterial;
  80694. _this._laserPointer.rotation.x = Math.PI / 2;
  80695. _this._laserPointer.position.z = -0.5;
  80696. _this._laserPointer.isVisible = false;
  80697. if (!webVRController.mesh) {
  80698. // Create an empty mesh that is used prior to loading the high quality model
  80699. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  80700. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  80701. preloadPointerPose.rotation.x = -0.7;
  80702. preloadMesh.addChild(preloadPointerPose);
  80703. webVRController.attachToMesh(preloadMesh);
  80704. }
  80705. _this._setLaserPointerParent(webVRController.mesh);
  80706. return _this;
  80707. }
  80708. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  80709. return this.webVRController.getForwardRay(length);
  80710. };
  80711. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  80712. _super.prototype._activatePointer.call(this);
  80713. this._laserPointer.isVisible = true;
  80714. };
  80715. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  80716. _super.prototype._deactivatePointer.call(this);
  80717. this._laserPointer.isVisible = false;
  80718. };
  80719. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  80720. this._laserPointer.material.emissiveColor = color;
  80721. };
  80722. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  80723. var makeNotPick = function (root) {
  80724. root.name += " laserPointer";
  80725. root.getChildMeshes().forEach(function (c) {
  80726. makeNotPick(c);
  80727. });
  80728. };
  80729. makeNotPick(mesh);
  80730. var childMeshes = mesh.getChildMeshes();
  80731. this.webVRController._pointingPoseNode = null;
  80732. for (var i = 0; i < childMeshes.length; i++) {
  80733. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  80734. mesh = childMeshes[i];
  80735. this.webVRController._pointingPoseNode = mesh;
  80736. break;
  80737. }
  80738. }
  80739. this._laserPointer.parent = mesh;
  80740. };
  80741. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  80742. this._laserPointer.scaling.y = distance;
  80743. this._laserPointer.position.z = -distance / 2;
  80744. };
  80745. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  80746. _super.prototype.dispose.call(this);
  80747. this._laserPointer.dispose();
  80748. };
  80749. return VRExperienceHelperControllerGazer;
  80750. }(VRExperienceHelperGazer));
  80751. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  80752. __extends(VRExperienceHelperCameraGazer, _super);
  80753. function VRExperienceHelperCameraGazer(getCamera, scene) {
  80754. var _this = _super.call(this, scene) || this;
  80755. _this.getCamera = getCamera;
  80756. return _this;
  80757. }
  80758. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  80759. var camera = this.getCamera();
  80760. if (camera) {
  80761. return camera.getForwardRay(length);
  80762. }
  80763. else {
  80764. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  80765. }
  80766. };
  80767. return VRExperienceHelperCameraGazer;
  80768. }(VRExperienceHelperGazer));
  80769. /**
  80770. * Helps to quickly add VR support to an existing scene.
  80771. * See http://doc.babylonjs.com/how_to/webvr_helper
  80772. */
  80773. var VRExperienceHelper = /** @class */ (function () {
  80774. /**
  80775. * Instantiates a VRExperienceHelper.
  80776. * Helps to quickly add VR support to an existing scene.
  80777. * @param scene The scene the VRExperienceHelper belongs to.
  80778. * @param webVROptions Options to modify the vr experience helper's behavior.
  80779. */
  80780. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  80781. if (webVROptions === void 0) { webVROptions = {}; }
  80782. var _this = this;
  80783. this.webVROptions = webVROptions;
  80784. // Can the system support WebVR, even if a headset isn't plugged in?
  80785. this._webVRsupported = false;
  80786. // If WebVR is supported, is a headset plugged in and are we ready to present?
  80787. this._webVRready = false;
  80788. // Are we waiting for the requestPresent callback to complete?
  80789. this._webVRrequesting = false;
  80790. // Are we presenting to the headset right now?
  80791. this._webVRpresenting = false;
  80792. // Are we presenting in the fullscreen fallback?
  80793. this._fullscreenVRpresenting = false;
  80794. /**
  80795. * Observable raised when entering VR.
  80796. */
  80797. this.onEnteringVRObservable = new BABYLON.Observable();
  80798. /**
  80799. * Observable raised when exiting VR.
  80800. */
  80801. this.onExitingVRObservable = new BABYLON.Observable();
  80802. /**
  80803. * Observable raised when controller mesh is loaded.
  80804. */
  80805. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80806. this._useCustomVRButton = false;
  80807. this._teleportationRequested = false;
  80808. this._teleportActive = false;
  80809. this._floorMeshesCollection = [];
  80810. this._rotationAllowed = true;
  80811. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  80812. this._rotationRightAsked = false;
  80813. this._rotationLeftAsked = false;
  80814. this._isDefaultTeleportationTarget = true;
  80815. this._teleportationFillColor = "#444444";
  80816. this._teleportationBorderColor = "#FFFFFF";
  80817. this._rotationAngle = 0;
  80818. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  80819. this._padSensibilityUp = 0.65;
  80820. this._padSensibilityDown = 0.35;
  80821. this.leftController = null;
  80822. this.rightController = null;
  80823. /**
  80824. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  80825. */
  80826. this.onNewMeshSelected = new BABYLON.Observable();
  80827. /**
  80828. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  80829. */
  80830. this.onNewMeshPicked = new BABYLON.Observable();
  80831. /**
  80832. * Observable raised before camera teleportation
  80833. */
  80834. this.onBeforeCameraTeleport = new BABYLON.Observable();
  80835. /**
  80836. * Observable raised after camera teleportation
  80837. */
  80838. this.onAfterCameraTeleport = new BABYLON.Observable();
  80839. /**
  80840. * Observable raised when current selected mesh gets unselected
  80841. */
  80842. this.onSelectedMeshUnselected = new BABYLON.Observable();
  80843. /**
  80844. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  80845. */
  80846. this.teleportationEnabled = true;
  80847. this._teleportationInitialized = false;
  80848. this._interactionsEnabled = false;
  80849. this._interactionsRequested = false;
  80850. this._displayGaze = true;
  80851. this._displayLaserPointer = true;
  80852. this._onResize = function () {
  80853. _this.moveButtonToBottomRight();
  80854. if (_this._fullscreenVRpresenting && _this._webVRready) {
  80855. _this.exitVR();
  80856. }
  80857. };
  80858. this._onFullscreenChange = function () {
  80859. if (document.fullscreen !== undefined) {
  80860. _this._fullscreenVRpresenting = document.fullscreen;
  80861. }
  80862. else if (document.mozFullScreen !== undefined) {
  80863. _this._fullscreenVRpresenting = document.mozFullScreen;
  80864. }
  80865. else if (document.webkitIsFullScreen !== undefined) {
  80866. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  80867. }
  80868. else if (document.msIsFullScreen !== undefined) {
  80869. _this._fullscreenVRpresenting = document.msIsFullScreen;
  80870. }
  80871. if (!_this._fullscreenVRpresenting && _this._canvas) {
  80872. _this.exitVR();
  80873. if (!_this._useCustomVRButton) {
  80874. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  80875. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  80876. }
  80877. }
  80878. };
  80879. this.beforeRender = function () {
  80880. if (_this.leftController && _this.leftController._activePointer) {
  80881. _this._castRayAndSelectObject(_this.leftController);
  80882. }
  80883. if (_this.rightController && _this.rightController._activePointer) {
  80884. _this._castRayAndSelectObject(_this.rightController);
  80885. }
  80886. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  80887. _this._castRayAndSelectObject(_this._cameraGazer);
  80888. }
  80889. else {
  80890. _this._cameraGazer._gazeTracker.isVisible = false;
  80891. }
  80892. };
  80893. this._onNewGamepadConnected = function (gamepad) {
  80894. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  80895. if (gamepad.leftStick) {
  80896. gamepad.onleftstickchanged(function (stickValues) {
  80897. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  80898. // Listening to classic/xbox gamepad only if no VR controller is active
  80899. if ((!_this.leftController && !_this.rightController) ||
  80900. ((_this.leftController && !_this.leftController._activePointer) &&
  80901. (_this.rightController && !_this.rightController._activePointer))) {
  80902. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  80903. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  80904. }
  80905. }
  80906. });
  80907. }
  80908. if (gamepad.rightStick) {
  80909. gamepad.onrightstickchanged(function (stickValues) {
  80910. if (_this._teleportationInitialized) {
  80911. _this._checkRotate(stickValues, _this._cameraGazer);
  80912. }
  80913. });
  80914. }
  80915. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  80916. gamepad.onbuttondown(function (buttonPressed) {
  80917. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80918. _this._cameraGazer._selectionPointerDown();
  80919. }
  80920. });
  80921. gamepad.onbuttonup(function (buttonPressed) {
  80922. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80923. _this._cameraGazer._selectionPointerUp();
  80924. }
  80925. });
  80926. }
  80927. }
  80928. else {
  80929. var webVRController = gamepad;
  80930. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  80931. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  80932. _this.rightController = controller;
  80933. }
  80934. else {
  80935. _this.leftController = controller;
  80936. }
  80937. _this._tryEnableInteractionOnController(controller);
  80938. }
  80939. };
  80940. // 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
  80941. this._tryEnableInteractionOnController = function (controller) {
  80942. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  80943. _this._enableInteractionOnController(controller);
  80944. }
  80945. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  80946. _this._enableTeleportationOnController(controller);
  80947. }
  80948. };
  80949. this._onNewGamepadDisconnected = function (gamepad) {
  80950. if (gamepad instanceof BABYLON.WebVRController) {
  80951. if (gamepad.hand === "left" && _this.leftController != null) {
  80952. _this.leftController.dispose();
  80953. _this.leftController = null;
  80954. }
  80955. if (gamepad.hand === "right" && _this.rightController != null) {
  80956. _this.rightController.dispose();
  80957. _this.rightController = null;
  80958. }
  80959. }
  80960. };
  80961. this._workingVector = BABYLON.Vector3.Zero();
  80962. this._workingQuaternion = BABYLON.Quaternion.Identity();
  80963. this._workingMatrix = BABYLON.Matrix.Identity();
  80964. this._scene = scene;
  80965. this._canvas = scene.getEngine().getRenderingCanvas();
  80966. // Parse options
  80967. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  80968. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  80969. }
  80970. if (webVROptions.createDeviceOrientationCamera === undefined) {
  80971. webVROptions.createDeviceOrientationCamera = true;
  80972. }
  80973. if (webVROptions.defaultHeight === undefined) {
  80974. webVROptions.defaultHeight = 1.7;
  80975. }
  80976. if (webVROptions.useCustomVRButton) {
  80977. this._useCustomVRButton = true;
  80978. if (webVROptions.customVRButton) {
  80979. this._btnVR = webVROptions.customVRButton;
  80980. }
  80981. }
  80982. if (webVROptions.rayLength) {
  80983. this._rayLength = webVROptions.rayLength;
  80984. }
  80985. this._defaultHeight = webVROptions.defaultHeight;
  80986. if (webVROptions.positionScale) {
  80987. this._rayLength *= webVROptions.positionScale;
  80988. this._defaultHeight *= webVROptions.positionScale;
  80989. }
  80990. // Set position
  80991. if (this._scene.activeCamera) {
  80992. this._position = this._scene.activeCamera.position.clone();
  80993. }
  80994. else {
  80995. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  80996. }
  80997. // Set non-vr camera
  80998. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  80999. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  81000. // Copy data from existing camera
  81001. if (this._scene.activeCamera) {
  81002. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  81003. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  81004. // Set rotation from previous camera
  81005. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  81006. var targetCamera = this._scene.activeCamera;
  81007. if (targetCamera.rotationQuaternion) {
  81008. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  81009. }
  81010. else {
  81011. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  81012. }
  81013. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  81014. }
  81015. }
  81016. this._scene.activeCamera = this._deviceOrientationCamera;
  81017. if (this._canvas) {
  81018. this._scene.activeCamera.attachControl(this._canvas);
  81019. }
  81020. }
  81021. else {
  81022. this._existingCamera = this._scene.activeCamera;
  81023. }
  81024. // Create VR cameras
  81025. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81026. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  81027. }
  81028. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  81029. this._webVRCamera.useStandingMatrix();
  81030. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  81031. // Create default button
  81032. if (!this._useCustomVRButton) {
  81033. this._btnVR = document.createElement("BUTTON");
  81034. this._btnVR.className = "babylonVRicon";
  81035. this._btnVR.id = "babylonVRiconbtn";
  81036. this._btnVR.title = "Click to switch to VR";
  81037. 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) }";
  81038. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  81039. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  81040. // css += ".babylonVRicon.vrdisplaysupported { }";
  81041. // css += ".babylonVRicon.vrdisplayready { }";
  81042. // css += ".babylonVRicon.vrdisplayrequesting { }";
  81043. var style = document.createElement('style');
  81044. style.appendChild(document.createTextNode(css));
  81045. document.getElementsByTagName('head')[0].appendChild(style);
  81046. this.moveButtonToBottomRight();
  81047. }
  81048. // VR button click event
  81049. if (this._btnVR) {
  81050. this._btnVR.addEventListener("click", function () {
  81051. if (!_this.isInVRMode) {
  81052. _this.enterVR();
  81053. }
  81054. else {
  81055. _this.exitVR();
  81056. }
  81057. });
  81058. }
  81059. // Window events
  81060. window.addEventListener("resize", this._onResize);
  81061. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  81062. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  81063. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  81064. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  81065. // Display vr button when headset is connected
  81066. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81067. this.displayVRButton();
  81068. }
  81069. else {
  81070. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  81071. if (e.vrDisplay) {
  81072. _this.displayVRButton();
  81073. }
  81074. });
  81075. }
  81076. // Exiting VR mode using 'ESC' key on desktop
  81077. this._onKeyDown = function (event) {
  81078. if (event.keyCode === 27 && _this.isInVRMode) {
  81079. _this.exitVR();
  81080. }
  81081. };
  81082. document.addEventListener("keydown", this._onKeyDown);
  81083. // Exiting VR mode double tapping the touch screen
  81084. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  81085. if (_this.isInVRMode) {
  81086. _this.exitVR();
  81087. if (_this._fullscreenVRpresenting) {
  81088. _this._scene.getEngine().switchFullscreen(true);
  81089. }
  81090. }
  81091. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  81092. // Listen for WebVR display changes
  81093. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  81094. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  81095. this._onVRRequestPresentStart = function () {
  81096. _this._webVRrequesting = true;
  81097. _this.updateButtonVisibility();
  81098. };
  81099. this._onVRRequestPresentComplete = function (success) {
  81100. _this._webVRrequesting = false;
  81101. _this.updateButtonVisibility();
  81102. };
  81103. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  81104. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  81105. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  81106. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81107. scene.onDisposeObservable.add(function () {
  81108. _this.dispose();
  81109. });
  81110. // Gamepad connection events
  81111. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  81112. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  81113. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  81114. this.updateButtonVisibility();
  81115. //create easing functions
  81116. this._circleEase = new BABYLON.CircleEase();
  81117. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81118. }
  81119. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  81120. /** Return this.onEnteringVRObservable
  81121. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  81122. */
  81123. get: function () {
  81124. return this.onEnteringVRObservable;
  81125. },
  81126. enumerable: true,
  81127. configurable: true
  81128. });
  81129. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  81130. /** Return this.onExitingVRObservable
  81131. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  81132. */
  81133. get: function () {
  81134. return this.onExitingVRObservable;
  81135. },
  81136. enumerable: true,
  81137. configurable: true
  81138. });
  81139. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  81140. /** Return this.onControllerMeshLoadedObservable
  81141. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  81142. */
  81143. get: function () {
  81144. return this.onControllerMeshLoadedObservable;
  81145. },
  81146. enumerable: true,
  81147. configurable: true
  81148. });
  81149. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  81150. /**
  81151. * The mesh used to display where the user is going to teleport.
  81152. */
  81153. get: function () {
  81154. return this._teleportationTarget;
  81155. },
  81156. /**
  81157. * Sets the mesh to be used to display where the user is going to teleport.
  81158. */
  81159. set: function (value) {
  81160. if (value) {
  81161. value.name = "teleportationTarget";
  81162. this._isDefaultTeleportationTarget = false;
  81163. this._teleportationTarget = value;
  81164. }
  81165. },
  81166. enumerable: true,
  81167. configurable: true
  81168. });
  81169. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  81170. /**
  81171. * The mesh used to display where the user is selecting,
  81172. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  81173. * See http://doc.babylonjs.com/resources/baking_transformations
  81174. */
  81175. get: function () {
  81176. return this._cameraGazer._gazeTracker;
  81177. },
  81178. set: function (value) {
  81179. if (value) {
  81180. this._cameraGazer._gazeTracker = value;
  81181. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  81182. this._cameraGazer._gazeTracker.isPickable = false;
  81183. this._cameraGazer._gazeTracker.isVisible = false;
  81184. this._cameraGazer._gazeTracker.name = "gazeTracker";
  81185. if (this.leftController) {
  81186. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81187. }
  81188. if (this.rightController) {
  81189. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  81190. }
  81191. }
  81192. },
  81193. enumerable: true,
  81194. configurable: true
  81195. });
  81196. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  81197. /**
  81198. * If the ray of the gaze should be displayed.
  81199. */
  81200. get: function () {
  81201. return this._displayGaze;
  81202. },
  81203. /**
  81204. * Sets if the ray of the gaze should be displayed.
  81205. */
  81206. set: function (value) {
  81207. this._displayGaze = value;
  81208. if (!value) {
  81209. this._cameraGazer._gazeTracker.isVisible = false;
  81210. if (this.leftController) {
  81211. this.leftController._gazeTracker.isVisible = false;
  81212. }
  81213. if (this.rightController) {
  81214. this.rightController._gazeTracker.isVisible = false;
  81215. }
  81216. }
  81217. },
  81218. enumerable: true,
  81219. configurable: true
  81220. });
  81221. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  81222. /**
  81223. * If the ray of the LaserPointer should be displayed.
  81224. */
  81225. get: function () {
  81226. return this._displayLaserPointer;
  81227. },
  81228. /**
  81229. * Sets if the ray of the LaserPointer should be displayed.
  81230. */
  81231. set: function (value) {
  81232. this._displayLaserPointer = value;
  81233. if (!value) {
  81234. if (this.rightController) {
  81235. this.rightController._deactivatePointer();
  81236. this.rightController._gazeTracker.isVisible = false;
  81237. }
  81238. if (this.leftController) {
  81239. this.leftController._deactivatePointer();
  81240. this.leftController._gazeTracker.isVisible = false;
  81241. }
  81242. }
  81243. else {
  81244. if (this.rightController) {
  81245. this.rightController._activatePointer();
  81246. }
  81247. else if (this.leftController) {
  81248. this.leftController._activatePointer();
  81249. }
  81250. }
  81251. },
  81252. enumerable: true,
  81253. configurable: true
  81254. });
  81255. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  81256. /**
  81257. * The deviceOrientationCamera used as the camera when not in VR.
  81258. */
  81259. get: function () {
  81260. return this._deviceOrientationCamera;
  81261. },
  81262. enumerable: true,
  81263. configurable: true
  81264. });
  81265. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  81266. /**
  81267. * Based on the current WebVR support, returns the current VR camera used.
  81268. */
  81269. get: function () {
  81270. if (this._webVRready) {
  81271. return this._webVRCamera;
  81272. }
  81273. else {
  81274. return this._scene.activeCamera;
  81275. }
  81276. },
  81277. enumerable: true,
  81278. configurable: true
  81279. });
  81280. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  81281. /**
  81282. * The webVRCamera which is used when in VR.
  81283. */
  81284. get: function () {
  81285. return this._webVRCamera;
  81286. },
  81287. enumerable: true,
  81288. configurable: true
  81289. });
  81290. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  81291. /**
  81292. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  81293. */
  81294. get: function () {
  81295. return this._vrDeviceOrientationCamera;
  81296. },
  81297. enumerable: true,
  81298. configurable: true
  81299. });
  81300. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  81301. get: function () {
  81302. var result = this._cameraGazer._teleportationRequestInitiated
  81303. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  81304. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  81305. return result;
  81306. },
  81307. enumerable: true,
  81308. configurable: true
  81309. });
  81310. // Raised when one of the controller has loaded successfully its associated default mesh
  81311. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  81312. if (this.leftController && this.leftController.webVRController == webVRController) {
  81313. if (webVRController.mesh) {
  81314. this.leftController._setLaserPointerParent(webVRController.mesh);
  81315. }
  81316. }
  81317. if (this.rightController && this.rightController.webVRController == webVRController) {
  81318. if (webVRController.mesh) {
  81319. this.rightController._setLaserPointerParent(webVRController.mesh);
  81320. }
  81321. }
  81322. try {
  81323. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  81324. }
  81325. catch (err) {
  81326. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  81327. }
  81328. };
  81329. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  81330. /**
  81331. * Gets a value indicating if we are currently in VR mode.
  81332. */
  81333. get: function () {
  81334. return this._webVRpresenting || this._fullscreenVRpresenting;
  81335. },
  81336. enumerable: true,
  81337. configurable: true
  81338. });
  81339. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  81340. var vrDisplay = this._scene.getEngine().getVRDevice();
  81341. if (vrDisplay) {
  81342. var wasPresenting = this._webVRpresenting;
  81343. // A VR display is connected
  81344. this._webVRpresenting = vrDisplay.isPresenting;
  81345. if (wasPresenting && !this._webVRpresenting)
  81346. this.exitVR();
  81347. }
  81348. else {
  81349. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  81350. }
  81351. this.updateButtonVisibility();
  81352. };
  81353. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  81354. this._webVRsupported = eventArgs.vrSupported;
  81355. this._webVRready = !!eventArgs.vrDisplay;
  81356. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  81357. this.updateButtonVisibility();
  81358. };
  81359. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  81360. if (this._canvas && !this._useCustomVRButton) {
  81361. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  81362. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  81363. }
  81364. };
  81365. VRExperienceHelper.prototype.displayVRButton = function () {
  81366. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  81367. document.body.appendChild(this._btnVR);
  81368. this._btnVRDisplayed = true;
  81369. }
  81370. };
  81371. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  81372. if (!this._btnVR || this._useCustomVRButton) {
  81373. return;
  81374. }
  81375. this._btnVR.className = "babylonVRicon";
  81376. if (this.isInVRMode) {
  81377. this._btnVR.className += " vrdisplaypresenting";
  81378. }
  81379. else {
  81380. if (this._webVRready)
  81381. this._btnVR.className += " vrdisplayready";
  81382. if (this._webVRsupported)
  81383. this._btnVR.className += " vrdisplaysupported";
  81384. if (this._webVRrequesting)
  81385. this._btnVR.className += " vrdisplayrequesting";
  81386. }
  81387. };
  81388. /**
  81389. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  81390. * Otherwise, will use the fullscreen API.
  81391. */
  81392. VRExperienceHelper.prototype.enterVR = function () {
  81393. if (this.onEnteringVRObservable) {
  81394. try {
  81395. this.onEnteringVRObservable.notifyObservers(this);
  81396. }
  81397. catch (err) {
  81398. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  81399. }
  81400. }
  81401. if (this._scene.activeCamera) {
  81402. this._position = this._scene.activeCamera.position.clone();
  81403. // make sure that we return to the last active camera
  81404. this._existingCamera = this._scene.activeCamera;
  81405. }
  81406. if (this._webVRrequesting)
  81407. return;
  81408. // If WebVR is supported and a headset is connected
  81409. if (this._webVRready) {
  81410. if (!this._webVRpresenting) {
  81411. this._webVRCamera.position = this._position;
  81412. this._scene.activeCamera = this._webVRCamera;
  81413. }
  81414. }
  81415. else if (this._vrDeviceOrientationCamera) {
  81416. this._vrDeviceOrientationCamera.position = this._position;
  81417. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  81418. this._scene.getEngine().switchFullscreen(true);
  81419. this.updateButtonVisibility();
  81420. }
  81421. if (this._scene.activeCamera && this._canvas) {
  81422. this._scene.activeCamera.attachControl(this._canvas);
  81423. }
  81424. if (this._interactionsEnabled) {
  81425. this._scene.registerBeforeRender(this.beforeRender);
  81426. }
  81427. };
  81428. /**
  81429. * Attempt to exit VR, or fullscreen.
  81430. */
  81431. VRExperienceHelper.prototype.exitVR = function () {
  81432. if (this.onExitingVRObservable) {
  81433. try {
  81434. this.onExitingVRObservable.notifyObservers(this);
  81435. }
  81436. catch (err) {
  81437. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  81438. }
  81439. }
  81440. if (this._webVRpresenting) {
  81441. this._scene.getEngine().disableVR();
  81442. }
  81443. if (this._scene.activeCamera) {
  81444. this._position = this._scene.activeCamera.position.clone();
  81445. }
  81446. if (this._deviceOrientationCamera) {
  81447. this._deviceOrientationCamera.position = this._position;
  81448. this._scene.activeCamera = this._deviceOrientationCamera;
  81449. if (this._canvas) {
  81450. this._scene.activeCamera.attachControl(this._canvas);
  81451. }
  81452. }
  81453. else if (this._existingCamera) {
  81454. this._existingCamera.position = this._position;
  81455. this._scene.activeCamera = this._existingCamera;
  81456. }
  81457. this.updateButtonVisibility();
  81458. if (this._interactionsEnabled) {
  81459. this._scene.unregisterBeforeRender(this.beforeRender);
  81460. }
  81461. };
  81462. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  81463. /**
  81464. * The position of the vr experience helper.
  81465. */
  81466. get: function () {
  81467. return this._position;
  81468. },
  81469. /**
  81470. * Sets the position of the vr experience helper.
  81471. */
  81472. set: function (value) {
  81473. this._position = value;
  81474. if (this._scene.activeCamera) {
  81475. this._scene.activeCamera.position = value;
  81476. }
  81477. },
  81478. enumerable: true,
  81479. configurable: true
  81480. });
  81481. /**
  81482. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  81483. */
  81484. VRExperienceHelper.prototype.enableInteractions = function () {
  81485. var _this = this;
  81486. if (!this._interactionsEnabled) {
  81487. this._interactionsRequested = true;
  81488. if (this.leftController) {
  81489. this._enableInteractionOnController(this.leftController);
  81490. }
  81491. if (this.rightController) {
  81492. this._enableInteractionOnController(this.rightController);
  81493. }
  81494. this.raySelectionPredicate = function (mesh) {
  81495. return mesh.isVisible;
  81496. };
  81497. this.meshSelectionPredicate = function (mesh) {
  81498. return true;
  81499. };
  81500. this._raySelectionPredicate = function (mesh) {
  81501. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  81502. && mesh.name.indexOf("teleportationTarget") === -1
  81503. && mesh.name.indexOf("torusTeleportation") === -1
  81504. && mesh.name.indexOf("laserPointer") === -1)) {
  81505. return _this.raySelectionPredicate(mesh);
  81506. }
  81507. return false;
  81508. };
  81509. this._interactionsEnabled = true;
  81510. }
  81511. };
  81512. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  81513. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  81514. if (this._floorMeshesCollection[i].id === mesh.id) {
  81515. return true;
  81516. }
  81517. }
  81518. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  81519. return true;
  81520. }
  81521. return false;
  81522. };
  81523. /**
  81524. * Adds a floor mesh to be used for teleportation.
  81525. * @param floorMesh the mesh to be used for teleportation.
  81526. */
  81527. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  81528. if (!this._floorMeshesCollection) {
  81529. return;
  81530. }
  81531. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  81532. return;
  81533. }
  81534. this._floorMeshesCollection.push(floorMesh);
  81535. };
  81536. /**
  81537. * Removes a floor mesh from being used for teleportation.
  81538. * @param floorMesh the mesh to be removed.
  81539. */
  81540. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  81541. if (!this._floorMeshesCollection) {
  81542. return;
  81543. }
  81544. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  81545. if (meshIndex !== -1) {
  81546. this._floorMeshesCollection.splice(meshIndex, 1);
  81547. }
  81548. };
  81549. /**
  81550. * Enables interactions and teleportation using the VR controllers and gaze.
  81551. * @param vrTeleportationOptions options to modify teleportation behavior.
  81552. */
  81553. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  81554. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  81555. if (!this._teleportationInitialized) {
  81556. this._teleportationRequested = true;
  81557. this.enableInteractions();
  81558. if (vrTeleportationOptions.floorMeshName) {
  81559. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  81560. }
  81561. if (vrTeleportationOptions.floorMeshes) {
  81562. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  81563. }
  81564. if (this.leftController != null) {
  81565. this._enableTeleportationOnController(this.leftController);
  81566. }
  81567. if (this.rightController != null) {
  81568. this._enableTeleportationOnController(this.rightController);
  81569. }
  81570. // Creates an image processing post process for the vignette not relying
  81571. // on the main scene configuration for image processing to reduce setup and spaces
  81572. // (gamma/linear) conflicts.
  81573. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  81574. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  81575. imageProcessingConfiguration.vignetteEnabled = true;
  81576. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  81577. this._webVRCamera.detachPostProcess(this._postProcessMove);
  81578. this._teleportationInitialized = true;
  81579. if (this._isDefaultTeleportationTarget) {
  81580. this._createTeleportationCircles();
  81581. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  81582. }
  81583. }
  81584. };
  81585. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  81586. var _this = this;
  81587. var controllerMesh = controller.webVRController.mesh;
  81588. if (controllerMesh) {
  81589. controller._interactionsEnabled = true;
  81590. controller._activatePointer();
  81591. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  81592. // Enabling / disabling laserPointer
  81593. if (_this._displayLaserPointer && stateObject.value === 1) {
  81594. if (controller._activePointer) {
  81595. controller._deactivatePointer();
  81596. }
  81597. else {
  81598. controller._activatePointer();
  81599. }
  81600. if (_this.displayGaze) {
  81601. controller._gazeTracker.isVisible = controller._activePointer;
  81602. }
  81603. }
  81604. });
  81605. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  81606. if (!controller._pointerDownOnMeshAsked) {
  81607. if (stateObject.value > _this._padSensibilityUp) {
  81608. controller._selectionPointerDown();
  81609. }
  81610. }
  81611. else if (stateObject.value < _this._padSensibilityDown) {
  81612. controller._selectionPointerUp();
  81613. }
  81614. });
  81615. }
  81616. };
  81617. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  81618. // Dont teleport if another gaze already requested teleportation
  81619. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  81620. return;
  81621. }
  81622. if (!gazer._teleportationRequestInitiated) {
  81623. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  81624. gazer._activatePointer();
  81625. gazer._teleportationRequestInitiated = true;
  81626. }
  81627. }
  81628. else {
  81629. // Listening to the proper controller values changes to confirm teleportation
  81630. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  81631. if (this._teleportActive) {
  81632. this._teleportCamera(this._haloCenter);
  81633. }
  81634. gazer._teleportationRequestInitiated = false;
  81635. }
  81636. }
  81637. };
  81638. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  81639. // Only rotate when user is not currently selecting a teleportation location
  81640. if (gazer._teleportationRequestInitiated) {
  81641. return;
  81642. }
  81643. if (!this._rotationLeftAsked) {
  81644. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  81645. this._rotationLeftAsked = true;
  81646. if (this._rotationAllowed) {
  81647. this._rotateCamera(false);
  81648. }
  81649. }
  81650. }
  81651. else {
  81652. if (stateObject.x > -this._padSensibilityDown) {
  81653. this._rotationLeftAsked = false;
  81654. }
  81655. }
  81656. if (!this._rotationRightAsked) {
  81657. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  81658. this._rotationRightAsked = true;
  81659. if (this._rotationAllowed) {
  81660. this._rotateCamera(true);
  81661. }
  81662. }
  81663. }
  81664. else {
  81665. if (stateObject.x < this._padSensibilityDown) {
  81666. this._rotationRightAsked = false;
  81667. }
  81668. }
  81669. };
  81670. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  81671. // Only teleport backwards when user is not currently selecting a teleportation location
  81672. if (gazer._teleportationRequestInitiated) {
  81673. return;
  81674. }
  81675. // Teleport backwards
  81676. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  81677. if (!gazer._teleportationBackRequestInitiated) {
  81678. if (!this.currentVRCamera) {
  81679. return;
  81680. }
  81681. // Get rotation and position of the current camera
  81682. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  81683. var position = this.currentVRCamera.position;
  81684. // If the camera has device position, use that instead
  81685. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  81686. rotation = this.currentVRCamera.deviceRotationQuaternion;
  81687. position = this.currentVRCamera.devicePosition;
  81688. }
  81689. // Get matrix with only the y rotation of the device rotation
  81690. rotation.toEulerAnglesToRef(this._workingVector);
  81691. this._workingVector.z = 0;
  81692. this._workingVector.x = 0;
  81693. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  81694. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  81695. // Rotate backwards ray by device rotation to cast at the ground behind the user
  81696. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  81697. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  81698. var ray = new BABYLON.Ray(position, this._workingVector);
  81699. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  81700. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  81701. this._teleportCamera(hit.pickedPoint);
  81702. }
  81703. gazer._teleportationBackRequestInitiated = true;
  81704. }
  81705. }
  81706. else {
  81707. gazer._teleportationBackRequestInitiated = false;
  81708. }
  81709. };
  81710. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  81711. var _this = this;
  81712. var controllerMesh = controller.webVRController.mesh;
  81713. if (controllerMesh) {
  81714. if (!controller._interactionsEnabled) {
  81715. this._enableInteractionOnController(controller);
  81716. }
  81717. controller._interactionsEnabled = true;
  81718. controller._teleportationEnabled = true;
  81719. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81720. controller._dpadPressed = false;
  81721. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  81722. controller._dpadPressed = stateObject.pressed;
  81723. if (!controller._dpadPressed) {
  81724. _this._rotationLeftAsked = false;
  81725. _this._rotationRightAsked = false;
  81726. controller._teleportationBackRequestInitiated = false;
  81727. }
  81728. });
  81729. }
  81730. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  81731. if (_this.teleportationEnabled) {
  81732. _this._checkTeleportBackwards(stateObject, controller);
  81733. _this._checkTeleportWithRay(stateObject, controller);
  81734. }
  81735. _this._checkRotate(stateObject, controller);
  81736. });
  81737. }
  81738. };
  81739. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  81740. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  81741. this._teleportationTarget.isPickable = false;
  81742. var length = 512;
  81743. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  81744. dynamicTexture.hasAlpha = true;
  81745. var context = dynamicTexture.getContext();
  81746. var centerX = length / 2;
  81747. var centerY = length / 2;
  81748. var radius = 200;
  81749. context.beginPath();
  81750. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  81751. context.fillStyle = this._teleportationFillColor;
  81752. context.fill();
  81753. context.lineWidth = 10;
  81754. context.strokeStyle = this._teleportationBorderColor;
  81755. context.stroke();
  81756. context.closePath();
  81757. dynamicTexture.update();
  81758. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  81759. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  81760. this._teleportationTarget.material = teleportationCircleMaterial;
  81761. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  81762. torus.isPickable = false;
  81763. torus.parent = this._teleportationTarget;
  81764. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  81765. var keys = [];
  81766. keys.push({
  81767. frame: 0,
  81768. value: 0
  81769. });
  81770. keys.push({
  81771. frame: 30,
  81772. value: 0.4
  81773. });
  81774. keys.push({
  81775. frame: 60,
  81776. value: 0
  81777. });
  81778. animationInnerCircle.setKeys(keys);
  81779. var easingFunction = new BABYLON.SineEase();
  81780. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81781. animationInnerCircle.setEasingFunction(easingFunction);
  81782. torus.animations = [];
  81783. torus.animations.push(animationInnerCircle);
  81784. this._scene.beginAnimation(torus, 0, 60, true);
  81785. this._hideTeleportationTarget();
  81786. };
  81787. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  81788. this._teleportActive = true;
  81789. if (this._teleportationInitialized) {
  81790. this._teleportationTarget.isVisible = true;
  81791. if (this._isDefaultTeleportationTarget) {
  81792. this._teleportationTarget.getChildren()[0].isVisible = true;
  81793. }
  81794. }
  81795. };
  81796. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  81797. this._teleportActive = false;
  81798. if (this._teleportationInitialized) {
  81799. this._teleportationTarget.isVisible = false;
  81800. if (this._isDefaultTeleportationTarget) {
  81801. this._teleportationTarget.getChildren()[0].isVisible = false;
  81802. }
  81803. }
  81804. };
  81805. VRExperienceHelper.prototype._rotateCamera = function (right) {
  81806. var _this = this;
  81807. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81808. return;
  81809. }
  81810. if (right) {
  81811. this._rotationAngle++;
  81812. }
  81813. else {
  81814. this._rotationAngle--;
  81815. }
  81816. this.currentVRCamera.animations = [];
  81817. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  81818. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81819. var animationRotationKeys = [];
  81820. animationRotationKeys.push({
  81821. frame: 0,
  81822. value: this.currentVRCamera.rotationQuaternion
  81823. });
  81824. animationRotationKeys.push({
  81825. frame: 6,
  81826. value: target
  81827. });
  81828. animationRotation.setKeys(animationRotationKeys);
  81829. animationRotation.setEasingFunction(this._circleEase);
  81830. this.currentVRCamera.animations.push(animationRotation);
  81831. this._postProcessMove.animations = [];
  81832. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81833. var vignetteWeightKeys = [];
  81834. vignetteWeightKeys.push({
  81835. frame: 0,
  81836. value: 0
  81837. });
  81838. vignetteWeightKeys.push({
  81839. frame: 3,
  81840. value: 4
  81841. });
  81842. vignetteWeightKeys.push({
  81843. frame: 6,
  81844. value: 0
  81845. });
  81846. animationPP.setKeys(vignetteWeightKeys);
  81847. animationPP.setEasingFunction(this._circleEase);
  81848. this._postProcessMove.animations.push(animationPP);
  81849. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81850. var vignetteStretchKeys = [];
  81851. vignetteStretchKeys.push({
  81852. frame: 0,
  81853. value: 0
  81854. });
  81855. vignetteStretchKeys.push({
  81856. frame: 3,
  81857. value: 10
  81858. });
  81859. vignetteStretchKeys.push({
  81860. frame: 6,
  81861. value: 0
  81862. });
  81863. animationPP2.setKeys(vignetteStretchKeys);
  81864. animationPP2.setEasingFunction(this._circleEase);
  81865. this._postProcessMove.animations.push(animationPP2);
  81866. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81867. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81868. this._postProcessMove.samples = 4;
  81869. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81870. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  81871. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81872. });
  81873. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  81874. };
  81875. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  81876. if (hit.pickedPoint) {
  81877. if (gazer._teleportationRequestInitiated) {
  81878. this._displayTeleportationTarget();
  81879. this._haloCenter.copyFrom(hit.pickedPoint);
  81880. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  81881. }
  81882. var pickNormal = hit.getNormal(true, false);
  81883. if (pickNormal) {
  81884. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81885. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81886. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  81887. }
  81888. this._teleportationTarget.position.y += 0.1;
  81889. }
  81890. };
  81891. VRExperienceHelper.prototype._teleportCamera = function (location) {
  81892. var _this = this;
  81893. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81894. return;
  81895. }
  81896. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  81897. // offset of the headset from the anchor.
  81898. if (this.webVRCamera.leftCamera) {
  81899. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  81900. this._workingVector.subtractInPlace(this.webVRCamera.position);
  81901. location.subtractToRef(this._workingVector, this._workingVector);
  81902. }
  81903. else {
  81904. this._workingVector.copyFrom(location);
  81905. }
  81906. // Add height to account for user's height offset
  81907. if (this.isInVRMode) {
  81908. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  81909. }
  81910. else {
  81911. this._workingVector.y += this._defaultHeight;
  81912. }
  81913. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  81914. // Create animation from the camera's position to the new location
  81915. this.currentVRCamera.animations = [];
  81916. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81917. var animationCameraTeleportationKeys = [{
  81918. frame: 0,
  81919. value: this.currentVRCamera.position
  81920. },
  81921. {
  81922. frame: 11,
  81923. value: this._workingVector
  81924. }
  81925. ];
  81926. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  81927. animationCameraTeleportation.setEasingFunction(this._circleEase);
  81928. this.currentVRCamera.animations.push(animationCameraTeleportation);
  81929. this._postProcessMove.animations = [];
  81930. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81931. var vignetteWeightKeys = [];
  81932. vignetteWeightKeys.push({
  81933. frame: 0,
  81934. value: 0
  81935. });
  81936. vignetteWeightKeys.push({
  81937. frame: 5,
  81938. value: 8
  81939. });
  81940. vignetteWeightKeys.push({
  81941. frame: 11,
  81942. value: 0
  81943. });
  81944. animationPP.setKeys(vignetteWeightKeys);
  81945. this._postProcessMove.animations.push(animationPP);
  81946. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81947. var vignetteStretchKeys = [];
  81948. vignetteStretchKeys.push({
  81949. frame: 0,
  81950. value: 0
  81951. });
  81952. vignetteStretchKeys.push({
  81953. frame: 5,
  81954. value: 10
  81955. });
  81956. vignetteStretchKeys.push({
  81957. frame: 11,
  81958. value: 0
  81959. });
  81960. animationPP2.setKeys(vignetteStretchKeys);
  81961. this._postProcessMove.animations.push(animationPP2);
  81962. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81963. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81964. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81965. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  81966. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81967. });
  81968. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  81969. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  81970. });
  81971. this._hideTeleportationTarget();
  81972. };
  81973. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  81974. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81975. return;
  81976. }
  81977. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  81978. // Moving the gazeTracker on the mesh face targetted
  81979. if (hit && hit.pickedPoint) {
  81980. if (this._displayGaze) {
  81981. var multiplier = 1;
  81982. gazer._gazeTracker.isVisible = true;
  81983. if (gazer._isActionableMesh) {
  81984. multiplier = 3;
  81985. }
  81986. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  81987. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  81988. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  81989. var pickNormal = hit.getNormal();
  81990. // To avoid z-fighting
  81991. var deltaFighting = 0.002;
  81992. if (pickNormal) {
  81993. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81994. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81995. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  81996. }
  81997. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  81998. if (gazer._gazeTracker.position.x < 0) {
  81999. gazer._gazeTracker.position.x += deltaFighting;
  82000. }
  82001. else {
  82002. gazer._gazeTracker.position.x -= deltaFighting;
  82003. }
  82004. if (gazer._gazeTracker.position.y < 0) {
  82005. gazer._gazeTracker.position.y += deltaFighting;
  82006. }
  82007. else {
  82008. gazer._gazeTracker.position.y -= deltaFighting;
  82009. }
  82010. if (gazer._gazeTracker.position.z < 0) {
  82011. gazer._gazeTracker.position.z += deltaFighting;
  82012. }
  82013. else {
  82014. gazer._gazeTracker.position.z -= deltaFighting;
  82015. }
  82016. }
  82017. // Changing the size of the laser pointer based on the distance from the targetted point
  82018. gazer._updatePointerDistance(hit.distance);
  82019. }
  82020. else {
  82021. gazer._gazeTracker.isVisible = false;
  82022. }
  82023. if (hit && hit.pickedMesh) {
  82024. gazer._currentHit = hit;
  82025. if (gazer._pointerDownOnMeshAsked) {
  82026. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  82027. }
  82028. // The object selected is the floor, we're in a teleportation scenario
  82029. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  82030. // Moving the teleportation area to this targetted point
  82031. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  82032. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  82033. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82034. }
  82035. gazer._currentMeshSelected = null;
  82036. if (gazer._teleportationRequestInitiated) {
  82037. this._moveTeleportationSelectorTo(hit, gazer);
  82038. }
  82039. return;
  82040. }
  82041. // If not, we're in a selection scenario
  82042. //this._teleportationAllowed = false;
  82043. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  82044. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  82045. this.onNewMeshPicked.notifyObservers(hit);
  82046. gazer._currentMeshSelected = hit.pickedMesh;
  82047. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  82048. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  82049. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  82050. gazer._isActionableMesh = true;
  82051. }
  82052. else {
  82053. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82054. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82055. gazer._isActionableMesh = false;
  82056. }
  82057. try {
  82058. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  82059. }
  82060. catch (err) {
  82061. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  82062. }
  82063. }
  82064. else {
  82065. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82066. gazer._currentMeshSelected = null;
  82067. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82068. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82069. }
  82070. }
  82071. }
  82072. else {
  82073. gazer._currentHit = null;
  82074. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82075. gazer._currentMeshSelected = null;
  82076. //this._teleportationAllowed = false;
  82077. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82078. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82079. }
  82080. };
  82081. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  82082. if (mesh) {
  82083. this.onSelectedMeshUnselected.notifyObservers(mesh);
  82084. }
  82085. };
  82086. /**
  82087. * Sets the color of the laser ray from the vr controllers.
  82088. * @param color new color for the ray.
  82089. */
  82090. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  82091. if (this.leftController) {
  82092. this.leftController._setLaserPointerColor(color);
  82093. }
  82094. if (this.rightController) {
  82095. this.rightController._setLaserPointerColor(color);
  82096. }
  82097. };
  82098. /**
  82099. * Sets the color of the ray from the vr headsets gaze.
  82100. * @param color new color for the ray.
  82101. */
  82102. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  82103. if (!this._cameraGazer._gazeTracker.material) {
  82104. return;
  82105. }
  82106. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  82107. if (this.leftController) {
  82108. this.leftController._gazeTracker.material.emissiveColor = color;
  82109. }
  82110. if (this.rightController) {
  82111. this.rightController._gazeTracker.material.emissiveColor = color;
  82112. }
  82113. };
  82114. /**
  82115. * Exits VR and disposes of the vr experience helper
  82116. */
  82117. VRExperienceHelper.prototype.dispose = function () {
  82118. if (this.isInVRMode) {
  82119. this.exitVR();
  82120. }
  82121. if (this._postProcessMove) {
  82122. this._postProcessMove.dispose();
  82123. }
  82124. if (this._webVRCamera) {
  82125. this._webVRCamera.dispose();
  82126. }
  82127. if (this._vrDeviceOrientationCamera) {
  82128. this._vrDeviceOrientationCamera.dispose();
  82129. }
  82130. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  82131. document.body.removeChild(this._btnVR);
  82132. }
  82133. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  82134. this._deviceOrientationCamera.dispose();
  82135. }
  82136. if (this._cameraGazer) {
  82137. this._cameraGazer.dispose();
  82138. }
  82139. if (this.leftController) {
  82140. this.leftController.dispose();
  82141. }
  82142. if (this.rightController) {
  82143. this.rightController.dispose();
  82144. }
  82145. if (this._teleportationTarget) {
  82146. this._teleportationTarget.dispose();
  82147. }
  82148. this._floorMeshesCollection = [];
  82149. document.removeEventListener("keydown", this._onKeyDown);
  82150. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82151. window.removeEventListener("resize", this._onResize);
  82152. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  82153. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  82154. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  82155. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  82156. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  82157. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  82158. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  82159. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82160. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  82161. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  82162. this._scene.unregisterBeforeRender(this.beforeRender);
  82163. };
  82164. /**
  82165. * Gets the name of the VRExperienceHelper class
  82166. * @returns "VRExperienceHelper"
  82167. */
  82168. VRExperienceHelper.prototype.getClassName = function () {
  82169. return "VRExperienceHelper";
  82170. };
  82171. return VRExperienceHelper;
  82172. }());
  82173. BABYLON.VRExperienceHelper = VRExperienceHelper;
  82174. })(BABYLON || (BABYLON = {}));
  82175. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  82176. // Mainly based on these 2 articles :
  82177. // 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
  82178. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  82179. var BABYLON;
  82180. (function (BABYLON) {
  82181. var JoystickAxis;
  82182. (function (JoystickAxis) {
  82183. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  82184. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  82185. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  82186. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  82187. var VirtualJoystick = /** @class */ (function () {
  82188. function VirtualJoystick(leftJoystick) {
  82189. var _this = this;
  82190. if (leftJoystick) {
  82191. this._leftJoystick = true;
  82192. }
  82193. else {
  82194. this._leftJoystick = false;
  82195. }
  82196. VirtualJoystick._globalJoystickIndex++;
  82197. // By default left & right arrow keys are moving the X
  82198. // and up & down keys are moving the Y
  82199. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82200. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82201. this.reverseLeftRight = false;
  82202. this.reverseUpDown = false;
  82203. // collections of pointers
  82204. this._touches = new BABYLON.StringDictionary();
  82205. this.deltaPosition = BABYLON.Vector3.Zero();
  82206. this._joystickSensibility = 25;
  82207. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82208. this._onResize = function (evt) {
  82209. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82210. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82211. if (VirtualJoystick.vjCanvas) {
  82212. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  82213. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  82214. }
  82215. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  82216. };
  82217. // injecting a canvas element on top of the canvas 3D game
  82218. if (!VirtualJoystick.vjCanvas) {
  82219. window.addEventListener("resize", this._onResize, false);
  82220. VirtualJoystick.vjCanvas = document.createElement("canvas");
  82221. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  82222. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  82223. VirtualJoystick.vjCanvas.width = window.innerWidth;
  82224. VirtualJoystick.vjCanvas.height = window.innerHeight;
  82225. VirtualJoystick.vjCanvas.style.width = "100%";
  82226. VirtualJoystick.vjCanvas.style.height = "100%";
  82227. VirtualJoystick.vjCanvas.style.position = "absolute";
  82228. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  82229. VirtualJoystick.vjCanvas.style.top = "0px";
  82230. VirtualJoystick.vjCanvas.style.left = "0px";
  82231. VirtualJoystick.vjCanvas.style.zIndex = "5";
  82232. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  82233. // Support for jQuery PEP polyfill
  82234. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  82235. var context = VirtualJoystick.vjCanvas.getContext('2d');
  82236. if (!context) {
  82237. throw new Error("Unable to create canvas for virtual joystick");
  82238. }
  82239. VirtualJoystick.vjCanvasContext = context;
  82240. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  82241. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82242. document.body.appendChild(VirtualJoystick.vjCanvas);
  82243. }
  82244. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  82245. this.pressed = false;
  82246. // default joystick color
  82247. this._joystickColor = "cyan";
  82248. this._joystickPointerID = -1;
  82249. // current joystick position
  82250. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  82251. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  82252. // origin joystick position
  82253. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  82254. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  82255. this._onPointerDownHandlerRef = function (evt) {
  82256. _this._onPointerDown(evt);
  82257. };
  82258. this._onPointerMoveHandlerRef = function (evt) {
  82259. _this._onPointerMove(evt);
  82260. };
  82261. this._onPointerUpHandlerRef = function (evt) {
  82262. _this._onPointerUp(evt);
  82263. };
  82264. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  82265. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  82266. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  82267. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  82268. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  82269. evt.preventDefault(); // Disables system menu
  82270. }, false);
  82271. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82272. }
  82273. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  82274. this._joystickSensibility = newJoystickSensibility;
  82275. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  82276. };
  82277. VirtualJoystick.prototype._onPointerDown = function (e) {
  82278. var positionOnScreenCondition;
  82279. e.preventDefault();
  82280. if (this._leftJoystick === true) {
  82281. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  82282. }
  82283. else {
  82284. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  82285. }
  82286. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  82287. // First contact will be dedicated to the virtual joystick
  82288. this._joystickPointerID = e.pointerId;
  82289. this._joystickPointerStartPos.x = e.clientX;
  82290. this._joystickPointerStartPos.y = e.clientY;
  82291. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  82292. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  82293. this._deltaJoystickVector.x = 0;
  82294. this._deltaJoystickVector.y = 0;
  82295. this.pressed = true;
  82296. this._touches.add(e.pointerId.toString(), e);
  82297. }
  82298. else {
  82299. // You can only trigger the action buttons with a joystick declared
  82300. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  82301. this._action();
  82302. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  82303. }
  82304. }
  82305. };
  82306. VirtualJoystick.prototype._onPointerMove = function (e) {
  82307. // If the current pointer is the one associated to the joystick (first touch contact)
  82308. if (this._joystickPointerID == e.pointerId) {
  82309. this._joystickPointerPos.x = e.clientX;
  82310. this._joystickPointerPos.y = e.clientY;
  82311. this._deltaJoystickVector = this._joystickPointerPos.clone();
  82312. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  82313. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  82314. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  82315. switch (this._axisTargetedByLeftAndRight) {
  82316. case JoystickAxis.X:
  82317. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  82318. break;
  82319. case JoystickAxis.Y:
  82320. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  82321. break;
  82322. case JoystickAxis.Z:
  82323. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  82324. break;
  82325. }
  82326. var directionUpDown = this.reverseUpDown ? 1 : -1;
  82327. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  82328. switch (this._axisTargetedByUpAndDown) {
  82329. case JoystickAxis.X:
  82330. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  82331. break;
  82332. case JoystickAxis.Y:
  82333. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  82334. break;
  82335. case JoystickAxis.Z:
  82336. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  82337. break;
  82338. }
  82339. }
  82340. else {
  82341. var data = this._touches.get(e.pointerId.toString());
  82342. if (data) {
  82343. data.x = e.clientX;
  82344. data.y = e.clientY;
  82345. }
  82346. }
  82347. };
  82348. VirtualJoystick.prototype._onPointerUp = function (e) {
  82349. if (this._joystickPointerID == e.pointerId) {
  82350. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  82351. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  82352. this._joystickPointerID = -1;
  82353. this.pressed = false;
  82354. }
  82355. else {
  82356. var touch = this._touches.get(e.pointerId.toString());
  82357. if (touch) {
  82358. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82359. }
  82360. }
  82361. this._deltaJoystickVector.x = 0;
  82362. this._deltaJoystickVector.y = 0;
  82363. this._touches.remove(e.pointerId.toString());
  82364. };
  82365. /**
  82366. * Change the color of the virtual joystick
  82367. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  82368. */
  82369. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  82370. this._joystickColor = newColor;
  82371. };
  82372. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  82373. this._action = action;
  82374. };
  82375. // Define which axis you'd like to control for left & right
  82376. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  82377. switch (axis) {
  82378. case JoystickAxis.X:
  82379. case JoystickAxis.Y:
  82380. case JoystickAxis.Z:
  82381. this._axisTargetedByLeftAndRight = axis;
  82382. break;
  82383. default:
  82384. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  82385. break;
  82386. }
  82387. };
  82388. // Define which axis you'd like to control for up & down
  82389. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  82390. switch (axis) {
  82391. case JoystickAxis.X:
  82392. case JoystickAxis.Y:
  82393. case JoystickAxis.Z:
  82394. this._axisTargetedByUpAndDown = axis;
  82395. break;
  82396. default:
  82397. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  82398. break;
  82399. }
  82400. };
  82401. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  82402. var _this = this;
  82403. if (this.pressed) {
  82404. this._touches.forEach(function (key, touch) {
  82405. if (touch.pointerId === _this._joystickPointerID) {
  82406. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  82407. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  82408. VirtualJoystick.vjCanvasContext.beginPath();
  82409. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82410. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82411. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  82412. VirtualJoystick.vjCanvasContext.stroke();
  82413. VirtualJoystick.vjCanvasContext.closePath();
  82414. VirtualJoystick.vjCanvasContext.beginPath();
  82415. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82416. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  82417. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  82418. VirtualJoystick.vjCanvasContext.stroke();
  82419. VirtualJoystick.vjCanvasContext.closePath();
  82420. VirtualJoystick.vjCanvasContext.beginPath();
  82421. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  82422. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  82423. VirtualJoystick.vjCanvasContext.stroke();
  82424. VirtualJoystick.vjCanvasContext.closePath();
  82425. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  82426. }
  82427. else {
  82428. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  82429. VirtualJoystick.vjCanvasContext.beginPath();
  82430. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  82431. VirtualJoystick.vjCanvasContext.beginPath();
  82432. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  82433. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  82434. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  82435. VirtualJoystick.vjCanvasContext.stroke();
  82436. VirtualJoystick.vjCanvasContext.closePath();
  82437. touch.prevX = touch.x;
  82438. touch.prevY = touch.y;
  82439. }
  82440. ;
  82441. });
  82442. }
  82443. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  82444. };
  82445. VirtualJoystick.prototype.releaseCanvas = function () {
  82446. if (VirtualJoystick.vjCanvas) {
  82447. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  82448. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  82449. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  82450. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  82451. window.removeEventListener("resize", this._onResize);
  82452. document.body.removeChild(VirtualJoystick.vjCanvas);
  82453. VirtualJoystick.vjCanvas = null;
  82454. }
  82455. };
  82456. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  82457. VirtualJoystick._globalJoystickIndex = 0;
  82458. return VirtualJoystick;
  82459. }());
  82460. BABYLON.VirtualJoystick = VirtualJoystick;
  82461. })(BABYLON || (BABYLON = {}));
  82462. //# sourceMappingURL=babylon.virtualJoystick.js.map
  82463. var BABYLON;
  82464. (function (BABYLON) {
  82465. // We're mainly based on the logic defined into the FreeCamera code
  82466. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  82467. __extends(VirtualJoysticksCamera, _super);
  82468. function VirtualJoysticksCamera(name, position, scene) {
  82469. var _this = _super.call(this, name, position, scene) || this;
  82470. _this.inputs.addVirtualJoystick();
  82471. return _this;
  82472. }
  82473. VirtualJoysticksCamera.prototype.getClassName = function () {
  82474. return "VirtualJoysticksCamera";
  82475. };
  82476. return VirtualJoysticksCamera;
  82477. }(BABYLON.FreeCamera));
  82478. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  82479. })(BABYLON || (BABYLON = {}));
  82480. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  82481. var BABYLON;
  82482. (function (BABYLON) {
  82483. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  82484. function FreeCameraVirtualJoystickInput() {
  82485. }
  82486. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  82487. return this._leftjoystick;
  82488. };
  82489. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  82490. return this._rightjoystick;
  82491. };
  82492. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  82493. if (this._leftjoystick) {
  82494. var camera = this.camera;
  82495. var speed = camera._computeLocalCameraSpeed() * 50;
  82496. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  82497. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  82498. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  82499. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  82500. if (!this._leftjoystick.pressed) {
  82501. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  82502. }
  82503. if (!this._rightjoystick.pressed) {
  82504. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  82505. }
  82506. }
  82507. };
  82508. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  82509. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  82510. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  82511. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  82512. this._leftjoystick.setJoystickSensibility(0.15);
  82513. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  82514. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  82515. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  82516. this._rightjoystick.reverseUpDown = true;
  82517. this._rightjoystick.setJoystickSensibility(0.05);
  82518. this._rightjoystick.setJoystickColor("yellow");
  82519. };
  82520. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  82521. this._leftjoystick.releaseCanvas();
  82522. this._rightjoystick.releaseCanvas();
  82523. };
  82524. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  82525. return "FreeCameraVirtualJoystickInput";
  82526. };
  82527. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  82528. return "virtualJoystick";
  82529. };
  82530. return FreeCameraVirtualJoystickInput;
  82531. }());
  82532. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  82533. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  82534. })(BABYLON || (BABYLON = {}));
  82535. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  82536. var BABYLON;
  82537. (function (BABYLON) {
  82538. var SimplificationSettings = /** @class */ (function () {
  82539. function SimplificationSettings(quality, distance, optimizeMesh) {
  82540. this.quality = quality;
  82541. this.distance = distance;
  82542. this.optimizeMesh = optimizeMesh;
  82543. }
  82544. return SimplificationSettings;
  82545. }());
  82546. BABYLON.SimplificationSettings = SimplificationSettings;
  82547. var SimplificationQueue = /** @class */ (function () {
  82548. function SimplificationQueue() {
  82549. this.running = false;
  82550. this._simplificationArray = [];
  82551. }
  82552. SimplificationQueue.prototype.addTask = function (task) {
  82553. this._simplificationArray.push(task);
  82554. };
  82555. SimplificationQueue.prototype.executeNext = function () {
  82556. var task = this._simplificationArray.pop();
  82557. if (task) {
  82558. this.running = true;
  82559. this.runSimplification(task);
  82560. }
  82561. else {
  82562. this.running = false;
  82563. }
  82564. };
  82565. SimplificationQueue.prototype.runSimplification = function (task) {
  82566. var _this = this;
  82567. if (task.parallelProcessing) {
  82568. //parallel simplifier
  82569. task.settings.forEach(function (setting) {
  82570. var simplifier = _this.getSimplifier(task);
  82571. simplifier.simplify(setting, function (newMesh) {
  82572. task.mesh.addLODLevel(setting.distance, newMesh);
  82573. newMesh.isVisible = true;
  82574. //check if it is the last
  82575. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  82576. //all done, run the success callback.
  82577. task.successCallback();
  82578. }
  82579. _this.executeNext();
  82580. });
  82581. });
  82582. }
  82583. else {
  82584. //single simplifier.
  82585. var simplifier = this.getSimplifier(task);
  82586. var runDecimation = function (setting, callback) {
  82587. simplifier.simplify(setting, function (newMesh) {
  82588. task.mesh.addLODLevel(setting.distance, newMesh);
  82589. newMesh.isVisible = true;
  82590. //run the next quality level
  82591. callback();
  82592. });
  82593. };
  82594. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  82595. runDecimation(task.settings[loop.index], function () {
  82596. loop.executeNext();
  82597. });
  82598. }, function () {
  82599. //execution ended, run the success callback.
  82600. if (task.successCallback) {
  82601. task.successCallback();
  82602. }
  82603. _this.executeNext();
  82604. });
  82605. }
  82606. };
  82607. SimplificationQueue.prototype.getSimplifier = function (task) {
  82608. switch (task.simplificationType) {
  82609. case SimplificationType.QUADRATIC:
  82610. default:
  82611. return new QuadraticErrorSimplification(task.mesh);
  82612. }
  82613. };
  82614. return SimplificationQueue;
  82615. }());
  82616. BABYLON.SimplificationQueue = SimplificationQueue;
  82617. /**
  82618. * The implemented types of simplification.
  82619. * At the moment only Quadratic Error Decimation is implemented.
  82620. */
  82621. var SimplificationType;
  82622. (function (SimplificationType) {
  82623. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  82624. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  82625. var DecimationTriangle = /** @class */ (function () {
  82626. function DecimationTriangle(vertices) {
  82627. this.vertices = vertices;
  82628. this.error = new Array(4);
  82629. this.deleted = false;
  82630. this.isDirty = false;
  82631. this.deletePending = false;
  82632. this.borderFactor = 0;
  82633. }
  82634. return DecimationTriangle;
  82635. }());
  82636. BABYLON.DecimationTriangle = DecimationTriangle;
  82637. var DecimationVertex = /** @class */ (function () {
  82638. function DecimationVertex(position, id) {
  82639. this.position = position;
  82640. this.id = id;
  82641. this.isBorder = true;
  82642. this.q = new QuadraticMatrix();
  82643. this.triangleCount = 0;
  82644. this.triangleStart = 0;
  82645. this.originalOffsets = [];
  82646. }
  82647. DecimationVertex.prototype.updatePosition = function (newPosition) {
  82648. this.position.copyFrom(newPosition);
  82649. };
  82650. return DecimationVertex;
  82651. }());
  82652. BABYLON.DecimationVertex = DecimationVertex;
  82653. var QuadraticMatrix = /** @class */ (function () {
  82654. function QuadraticMatrix(data) {
  82655. this.data = new Array(10);
  82656. for (var i = 0; i < 10; ++i) {
  82657. if (data && data[i]) {
  82658. this.data[i] = data[i];
  82659. }
  82660. else {
  82661. this.data[i] = 0;
  82662. }
  82663. }
  82664. }
  82665. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  82666. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  82667. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  82668. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  82669. return det;
  82670. };
  82671. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  82672. for (var i = 0; i < 10; ++i) {
  82673. this.data[i] += matrix.data[i];
  82674. }
  82675. };
  82676. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  82677. for (var i = 0; i < 10; ++i) {
  82678. this.data[i] += data[i];
  82679. }
  82680. };
  82681. QuadraticMatrix.prototype.add = function (matrix) {
  82682. var m = new QuadraticMatrix();
  82683. for (var i = 0; i < 10; ++i) {
  82684. m.data[i] = this.data[i] + matrix.data[i];
  82685. }
  82686. return m;
  82687. };
  82688. QuadraticMatrix.FromData = function (a, b, c, d) {
  82689. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  82690. };
  82691. //returning an array to avoid garbage collection
  82692. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  82693. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  82694. };
  82695. return QuadraticMatrix;
  82696. }());
  82697. BABYLON.QuadraticMatrix = QuadraticMatrix;
  82698. var Reference = /** @class */ (function () {
  82699. function Reference(vertexId, triangleId) {
  82700. this.vertexId = vertexId;
  82701. this.triangleId = triangleId;
  82702. }
  82703. return Reference;
  82704. }());
  82705. BABYLON.Reference = Reference;
  82706. /**
  82707. * An implementation of the Quadratic Error simplification algorithm.
  82708. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  82709. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  82710. * @author RaananW
  82711. */
  82712. var QuadraticErrorSimplification = /** @class */ (function () {
  82713. function QuadraticErrorSimplification(_mesh) {
  82714. this._mesh = _mesh;
  82715. this.syncIterations = 5000;
  82716. this.aggressiveness = 7;
  82717. this.decimationIterations = 100;
  82718. this.boundingBoxEpsilon = BABYLON.Epsilon;
  82719. }
  82720. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  82721. var _this = this;
  82722. this.initDecimatedMesh();
  82723. //iterating through the submeshes array, one after the other.
  82724. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  82725. _this.initWithMesh(loop.index, function () {
  82726. _this.runDecimation(settings, loop.index, function () {
  82727. loop.executeNext();
  82728. });
  82729. }, settings.optimizeMesh);
  82730. }, function () {
  82731. setTimeout(function () {
  82732. successCallback(_this._reconstructedMesh);
  82733. }, 0);
  82734. });
  82735. };
  82736. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  82737. var _this = this;
  82738. var targetCount = ~~(this.triangles.length * settings.quality);
  82739. var deletedTriangles = 0;
  82740. var triangleCount = this.triangles.length;
  82741. var iterationFunction = function (iteration, callback) {
  82742. setTimeout(function () {
  82743. if (iteration % 5 === 0) {
  82744. _this.updateMesh(iteration === 0);
  82745. }
  82746. for (var i = 0; i < _this.triangles.length; ++i) {
  82747. _this.triangles[i].isDirty = false;
  82748. }
  82749. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  82750. var trianglesIterator = function (i) {
  82751. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  82752. var t = _this.triangles[tIdx];
  82753. if (!t)
  82754. return;
  82755. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  82756. return;
  82757. }
  82758. for (var j = 0; j < 3; ++j) {
  82759. if (t.error[j] < threshold) {
  82760. var deleted0 = [];
  82761. var deleted1 = [];
  82762. var v0 = t.vertices[j];
  82763. var v1 = t.vertices[(j + 1) % 3];
  82764. if (v0.isBorder || v1.isBorder)
  82765. continue;
  82766. var p = BABYLON.Vector3.Zero();
  82767. var n = BABYLON.Vector3.Zero();
  82768. var uv = BABYLON.Vector2.Zero();
  82769. var color = new BABYLON.Color4(0, 0, 0, 1);
  82770. _this.calculateError(v0, v1, p, n, uv, color);
  82771. var delTr = new Array();
  82772. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  82773. continue;
  82774. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  82775. continue;
  82776. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  82777. continue;
  82778. var uniqueArray = new Array();
  82779. delTr.forEach(function (deletedT) {
  82780. if (uniqueArray.indexOf(deletedT) === -1) {
  82781. deletedT.deletePending = true;
  82782. uniqueArray.push(deletedT);
  82783. }
  82784. });
  82785. if (uniqueArray.length % 2 !== 0) {
  82786. continue;
  82787. }
  82788. v0.q = v1.q.add(v0.q);
  82789. v0.updatePosition(p);
  82790. var tStart = _this.references.length;
  82791. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  82792. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  82793. var tCount = _this.references.length - tStart;
  82794. if (tCount <= v0.triangleCount) {
  82795. if (tCount) {
  82796. for (var c = 0; c < tCount; c++) {
  82797. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  82798. }
  82799. }
  82800. }
  82801. else {
  82802. v0.triangleStart = tStart;
  82803. }
  82804. v0.triangleCount = tCount;
  82805. break;
  82806. }
  82807. }
  82808. };
  82809. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  82810. }, 0);
  82811. };
  82812. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  82813. if (triangleCount - deletedTriangles <= targetCount)
  82814. loop.breakLoop();
  82815. else {
  82816. iterationFunction(loop.index, function () {
  82817. loop.executeNext();
  82818. });
  82819. }
  82820. }, function () {
  82821. setTimeout(function () {
  82822. //reconstruct this part of the mesh
  82823. _this.reconstructMesh(submeshIndex);
  82824. successCallback();
  82825. }, 0);
  82826. });
  82827. };
  82828. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  82829. var _this = this;
  82830. this.vertices = [];
  82831. this.triangles = [];
  82832. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82833. var indices = this._mesh.getIndices();
  82834. var submesh = this._mesh.subMeshes[submeshIndex];
  82835. var findInVertices = function (positionToSearch) {
  82836. if (optimizeMesh) {
  82837. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  82838. if (_this.vertices[ii].position.equals(positionToSearch)) {
  82839. return _this.vertices[ii];
  82840. }
  82841. }
  82842. }
  82843. return null;
  82844. };
  82845. var vertexReferences = [];
  82846. var vertexInit = function (i) {
  82847. if (!positionData) {
  82848. return;
  82849. }
  82850. var offset = i + submesh.verticesStart;
  82851. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  82852. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  82853. vertex.originalOffsets.push(offset);
  82854. if (vertex.id === _this.vertices.length) {
  82855. _this.vertices.push(vertex);
  82856. }
  82857. vertexReferences.push(vertex.id);
  82858. };
  82859. //var totalVertices = mesh.getTotalVertices();
  82860. var totalVertices = submesh.verticesCount;
  82861. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  82862. var indicesInit = function (i) {
  82863. if (!indices) {
  82864. return;
  82865. }
  82866. var offset = (submesh.indexStart / 3) + i;
  82867. var pos = (offset * 3);
  82868. var i0 = indices[pos + 0];
  82869. var i1 = indices[pos + 1];
  82870. var i2 = indices[pos + 2];
  82871. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  82872. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  82873. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  82874. var triangle = new DecimationTriangle([v0, v1, v2]);
  82875. triangle.originalOffset = pos;
  82876. _this.triangles.push(triangle);
  82877. };
  82878. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  82879. _this.init(callback);
  82880. });
  82881. });
  82882. };
  82883. QuadraticErrorSimplification.prototype.init = function (callback) {
  82884. var _this = this;
  82885. var triangleInit1 = function (i) {
  82886. var t = _this.triangles[i];
  82887. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  82888. for (var j = 0; j < 3; j++) {
  82889. 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))));
  82890. }
  82891. };
  82892. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  82893. var triangleInit2 = function (i) {
  82894. var t = _this.triangles[i];
  82895. for (var j = 0; j < 3; ++j) {
  82896. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  82897. }
  82898. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82899. };
  82900. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  82901. callback();
  82902. });
  82903. });
  82904. };
  82905. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  82906. var newTriangles = [];
  82907. var i;
  82908. for (i = 0; i < this.vertices.length; ++i) {
  82909. this.vertices[i].triangleCount = 0;
  82910. }
  82911. var t;
  82912. var j;
  82913. for (i = 0; i < this.triangles.length; ++i) {
  82914. if (!this.triangles[i].deleted) {
  82915. t = this.triangles[i];
  82916. for (j = 0; j < 3; ++j) {
  82917. t.vertices[j].triangleCount = 1;
  82918. }
  82919. newTriangles.push(t);
  82920. }
  82921. }
  82922. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  82923. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  82924. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  82925. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  82926. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  82927. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82928. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  82929. var vertexCount = 0;
  82930. for (i = 0; i < this.vertices.length; ++i) {
  82931. var vertex = this.vertices[i];
  82932. vertex.id = vertexCount;
  82933. if (vertex.triangleCount) {
  82934. vertex.originalOffsets.forEach(function (originalOffset) {
  82935. if (!normalData) {
  82936. return;
  82937. }
  82938. newPositionData.push(vertex.position.x);
  82939. newPositionData.push(vertex.position.y);
  82940. newPositionData.push(vertex.position.z);
  82941. newNormalData.push(normalData[originalOffset * 3]);
  82942. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  82943. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  82944. if (uvs && uvs.length) {
  82945. newUVsData.push(uvs[(originalOffset * 2)]);
  82946. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  82947. }
  82948. else if (colorsData && colorsData.length) {
  82949. newColorsData.push(colorsData[(originalOffset * 4)]);
  82950. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  82951. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  82952. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  82953. }
  82954. ++vertexCount;
  82955. });
  82956. }
  82957. }
  82958. var startingIndex = this._reconstructedMesh.getTotalIndices();
  82959. var startingVertex = this._reconstructedMesh.getTotalVertices();
  82960. var submeshesArray = this._reconstructedMesh.subMeshes;
  82961. this._reconstructedMesh.subMeshes = [];
  82962. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  82963. var originalIndices = this._mesh.getIndices();
  82964. for (i = 0; i < newTriangles.length; ++i) {
  82965. t = newTriangles[i]; //now get the new referencing point for each vertex
  82966. [0, 1, 2].forEach(function (idx) {
  82967. var id = originalIndices[t.originalOffset + idx];
  82968. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  82969. if (offset < 0)
  82970. offset = 0;
  82971. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  82972. });
  82973. }
  82974. //overwriting the old vertex buffers and indices.
  82975. this._reconstructedMesh.setIndices(newIndicesArray);
  82976. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  82977. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  82978. if (newUVsData.length > 0)
  82979. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  82980. if (newColorsData.length > 0)
  82981. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  82982. //create submesh
  82983. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  82984. if (submeshIndex > 0) {
  82985. this._reconstructedMesh.subMeshes = [];
  82986. submeshesArray.forEach(function (submesh) {
  82987. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  82988. });
  82989. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  82990. }
  82991. };
  82992. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  82993. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  82994. this._reconstructedMesh.material = this._mesh.material;
  82995. this._reconstructedMesh.parent = this._mesh.parent;
  82996. this._reconstructedMesh.isVisible = false;
  82997. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  82998. };
  82999. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  83000. for (var i = 0; i < vertex1.triangleCount; ++i) {
  83001. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  83002. if (t.deleted)
  83003. continue;
  83004. var s = this.references[vertex1.triangleStart + i].vertexId;
  83005. var v1 = t.vertices[(s + 1) % 3];
  83006. var v2 = t.vertices[(s + 2) % 3];
  83007. if ((v1 === vertex2 || v2 === vertex2)) {
  83008. deletedArray[i] = true;
  83009. delTr.push(t);
  83010. continue;
  83011. }
  83012. var d1 = v1.position.subtract(point);
  83013. d1 = d1.normalize();
  83014. var d2 = v2.position.subtract(point);
  83015. d2 = d2.normalize();
  83016. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  83017. return true;
  83018. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  83019. deletedArray[i] = false;
  83020. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  83021. return true;
  83022. }
  83023. return false;
  83024. };
  83025. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  83026. var newDeleted = deletedTriangles;
  83027. for (var i = 0; i < vertex.triangleCount; ++i) {
  83028. var ref = this.references[vertex.triangleStart + i];
  83029. var t = this.triangles[ref.triangleId];
  83030. if (t.deleted)
  83031. continue;
  83032. if (deletedArray[i] && t.deletePending) {
  83033. t.deleted = true;
  83034. newDeleted++;
  83035. continue;
  83036. }
  83037. t.vertices[ref.vertexId] = origVertex;
  83038. t.isDirty = true;
  83039. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  83040. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  83041. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  83042. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83043. this.references.push(ref);
  83044. }
  83045. return newDeleted;
  83046. };
  83047. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  83048. for (var i = 0; i < this.vertices.length; ++i) {
  83049. var vCount = [];
  83050. var vId = [];
  83051. var v = this.vertices[i];
  83052. var j;
  83053. for (j = 0; j < v.triangleCount; ++j) {
  83054. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  83055. for (var ii = 0; ii < 3; ii++) {
  83056. var ofs = 0;
  83057. var vv = triangle.vertices[ii];
  83058. while (ofs < vCount.length) {
  83059. if (vId[ofs] === vv.id)
  83060. break;
  83061. ++ofs;
  83062. }
  83063. if (ofs === vCount.length) {
  83064. vCount.push(1);
  83065. vId.push(vv.id);
  83066. }
  83067. else {
  83068. vCount[ofs]++;
  83069. }
  83070. }
  83071. }
  83072. for (j = 0; j < vCount.length; ++j) {
  83073. if (vCount[j] === 1) {
  83074. this.vertices[vId[j]].isBorder = true;
  83075. }
  83076. else {
  83077. this.vertices[vId[j]].isBorder = false;
  83078. }
  83079. }
  83080. }
  83081. };
  83082. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  83083. if (identifyBorders === void 0) { identifyBorders = false; }
  83084. var i;
  83085. if (!identifyBorders) {
  83086. var newTrianglesVector = [];
  83087. for (i = 0; i < this.triangles.length; ++i) {
  83088. if (!this.triangles[i].deleted) {
  83089. newTrianglesVector.push(this.triangles[i]);
  83090. }
  83091. }
  83092. this.triangles = newTrianglesVector;
  83093. }
  83094. for (i = 0; i < this.vertices.length; ++i) {
  83095. this.vertices[i].triangleCount = 0;
  83096. this.vertices[i].triangleStart = 0;
  83097. }
  83098. var t;
  83099. var j;
  83100. var v;
  83101. for (i = 0; i < this.triangles.length; ++i) {
  83102. t = this.triangles[i];
  83103. for (j = 0; j < 3; ++j) {
  83104. v = t.vertices[j];
  83105. v.triangleCount++;
  83106. }
  83107. }
  83108. var tStart = 0;
  83109. for (i = 0; i < this.vertices.length; ++i) {
  83110. this.vertices[i].triangleStart = tStart;
  83111. tStart += this.vertices[i].triangleCount;
  83112. this.vertices[i].triangleCount = 0;
  83113. }
  83114. var newReferences = new Array(this.triangles.length * 3);
  83115. for (i = 0; i < this.triangles.length; ++i) {
  83116. t = this.triangles[i];
  83117. for (j = 0; j < 3; ++j) {
  83118. v = t.vertices[j];
  83119. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  83120. v.triangleCount++;
  83121. }
  83122. }
  83123. this.references = newReferences;
  83124. if (identifyBorders) {
  83125. this.identifyBorder();
  83126. }
  83127. };
  83128. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  83129. var x = point.x;
  83130. var y = point.y;
  83131. var z = point.z;
  83132. 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
  83133. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  83134. };
  83135. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  83136. var q = vertex1.q.add(vertex2.q);
  83137. var border = vertex1.isBorder && vertex2.isBorder;
  83138. var error = 0;
  83139. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  83140. if (qDet !== 0 && !border) {
  83141. if (!pointResult) {
  83142. pointResult = BABYLON.Vector3.Zero();
  83143. }
  83144. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  83145. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  83146. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  83147. error = this.vertexError(q, pointResult);
  83148. }
  83149. else {
  83150. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  83151. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  83152. var error1 = this.vertexError(q, vertex1.position);
  83153. var error2 = this.vertexError(q, vertex2.position);
  83154. var error3 = this.vertexError(q, p3);
  83155. error = Math.min(error1, error2, error3);
  83156. if (error === error1) {
  83157. if (pointResult) {
  83158. pointResult.copyFrom(vertex1.position);
  83159. }
  83160. }
  83161. else if (error === error2) {
  83162. if (pointResult) {
  83163. pointResult.copyFrom(vertex2.position);
  83164. }
  83165. }
  83166. else {
  83167. if (pointResult) {
  83168. pointResult.copyFrom(p3);
  83169. }
  83170. }
  83171. }
  83172. return error;
  83173. };
  83174. return QuadraticErrorSimplification;
  83175. }());
  83176. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  83177. })(BABYLON || (BABYLON = {}));
  83178. //# sourceMappingURL=babylon.meshSimplification.js.map
  83179. var BABYLON;
  83180. (function (BABYLON) {
  83181. var MeshLODLevel = /** @class */ (function () {
  83182. function MeshLODLevel(distance, mesh) {
  83183. this.distance = distance;
  83184. this.mesh = mesh;
  83185. }
  83186. return MeshLODLevel;
  83187. }());
  83188. BABYLON.MeshLODLevel = MeshLODLevel;
  83189. })(BABYLON || (BABYLON = {}));
  83190. //# sourceMappingURL=babylon.meshLODLevel.js.map
  83191. var BABYLON;
  83192. (function (BABYLON) {
  83193. /**
  83194. * Defines the root class used to create scene optimization to use with SceneOptimizer
  83195. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83196. */
  83197. var SceneOptimization = /** @class */ (function () {
  83198. /**
  83199. * Creates the SceneOptimization object
  83200. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83201. * @param desc defines the description associated with the optimization
  83202. */
  83203. function SceneOptimization(
  83204. /**
  83205. * Defines the priority of this optimization (0 by default which means first in the list)
  83206. */
  83207. priority) {
  83208. if (priority === void 0) { priority = 0; }
  83209. this.priority = priority;
  83210. }
  83211. /**
  83212. * Gets a string describing the action executed by the current optimization
  83213. * @returns description string
  83214. */
  83215. SceneOptimization.prototype.getDescription = function () {
  83216. return "";
  83217. };
  83218. /**
  83219. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83220. * @param scene defines the current scene where to apply this optimization
  83221. * @param optimizer defines the current optimizer
  83222. * @returns true if everything that can be done was applied
  83223. */
  83224. SceneOptimization.prototype.apply = function (scene, optimizer) {
  83225. return true;
  83226. };
  83227. ;
  83228. return SceneOptimization;
  83229. }());
  83230. BABYLON.SceneOptimization = SceneOptimization;
  83231. /**
  83232. * Defines an optimization used to reduce the size of render target textures
  83233. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83234. */
  83235. var TextureOptimization = /** @class */ (function (_super) {
  83236. __extends(TextureOptimization, _super);
  83237. /**
  83238. * Creates the TextureOptimization object
  83239. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83240. * @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
  83241. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83242. */
  83243. function TextureOptimization(
  83244. /**
  83245. * Defines the priority of this optimization (0 by default which means first in the list)
  83246. */
  83247. priority,
  83248. /**
  83249. * 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
  83250. */
  83251. maximumSize,
  83252. /**
  83253. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  83254. */
  83255. step) {
  83256. if (priority === void 0) { priority = 0; }
  83257. if (maximumSize === void 0) { maximumSize = 1024; }
  83258. if (step === void 0) { step = 0.5; }
  83259. var _this = _super.call(this, priority) || this;
  83260. _this.priority = priority;
  83261. _this.maximumSize = maximumSize;
  83262. _this.step = step;
  83263. return _this;
  83264. }
  83265. /**
  83266. * Gets a string describing the action executed by the current optimization
  83267. * @returns description string
  83268. */
  83269. TextureOptimization.prototype.getDescription = function () {
  83270. return "Reducing render target texture size to " + this.maximumSize;
  83271. };
  83272. /**
  83273. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83274. * @param scene defines the current scene where to apply this optimization
  83275. * @param optimizer defines the current optimizer
  83276. * @returns true if everything that can be done was applied
  83277. */
  83278. TextureOptimization.prototype.apply = function (scene, optimizer) {
  83279. var allDone = true;
  83280. for (var index = 0; index < scene.textures.length; index++) {
  83281. var texture = scene.textures[index];
  83282. if (!texture.canRescale || texture.getContext) {
  83283. continue;
  83284. }
  83285. var currentSize = texture.getSize();
  83286. var maxDimension = Math.max(currentSize.width, currentSize.height);
  83287. if (maxDimension > this.maximumSize) {
  83288. texture.scale(this.step);
  83289. allDone = false;
  83290. }
  83291. }
  83292. return allDone;
  83293. };
  83294. return TextureOptimization;
  83295. }(SceneOptimization));
  83296. BABYLON.TextureOptimization = TextureOptimization;
  83297. /**
  83298. * Defines an optimization used to increase or decrease the rendering resolution
  83299. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83300. */
  83301. var HardwareScalingOptimization = /** @class */ (function (_super) {
  83302. __extends(HardwareScalingOptimization, _super);
  83303. /**
  83304. * Creates the HardwareScalingOptimization object
  83305. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83306. * @param maximumScale defines the maximum scale to use (2 by default)
  83307. * @param step defines the step to use between two passes (0.5 by default)
  83308. */
  83309. function HardwareScalingOptimization(
  83310. /**
  83311. * Defines the priority of this optimization (0 by default which means first in the list)
  83312. */
  83313. priority,
  83314. /**
  83315. * Defines the maximum scale to use (2 by default)
  83316. */
  83317. maximumScale,
  83318. /**
  83319. * Defines the step to use between two passes (0.5 by default)
  83320. */
  83321. step) {
  83322. if (priority === void 0) { priority = 0; }
  83323. if (maximumScale === void 0) { maximumScale = 2; }
  83324. if (step === void 0) { step = 0.25; }
  83325. var _this = _super.call(this, priority) || this;
  83326. _this.priority = priority;
  83327. _this.maximumScale = maximumScale;
  83328. _this.step = step;
  83329. _this._currentScale = -1;
  83330. _this._directionOffset = 1;
  83331. return _this;
  83332. }
  83333. /**
  83334. * Gets a string describing the action executed by the current optimization
  83335. * @return description string
  83336. */
  83337. HardwareScalingOptimization.prototype.getDescription = function () {
  83338. return "Setting hardware scaling level to " + this._currentScale;
  83339. };
  83340. /**
  83341. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83342. * @param scene defines the current scene where to apply this optimization
  83343. * @param optimizer defines the current optimizer
  83344. * @returns true if everything that can be done was applied
  83345. */
  83346. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  83347. if (this._currentScale === -1) {
  83348. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  83349. if (this._currentScale > this.maximumScale) {
  83350. this._directionOffset = -1;
  83351. }
  83352. }
  83353. this._currentScale += this._directionOffset * this.step;
  83354. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  83355. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  83356. };
  83357. ;
  83358. return HardwareScalingOptimization;
  83359. }(SceneOptimization));
  83360. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  83361. /**
  83362. * Defines an optimization used to remove shadows
  83363. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83364. */
  83365. var ShadowsOptimization = /** @class */ (function (_super) {
  83366. __extends(ShadowsOptimization, _super);
  83367. function ShadowsOptimization() {
  83368. return _super !== null && _super.apply(this, arguments) || this;
  83369. }
  83370. /**
  83371. * Gets a string describing the action executed by the current optimization
  83372. * @return description string
  83373. */
  83374. ShadowsOptimization.prototype.getDescription = function () {
  83375. return "Turning shadows on/off";
  83376. };
  83377. /**
  83378. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83379. * @param scene defines the current scene where to apply this optimization
  83380. * @param optimizer defines the current optimizer
  83381. * @returns true if everything that can be done was applied
  83382. */
  83383. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  83384. scene.shadowsEnabled = optimizer.isInImprovementMode;
  83385. return true;
  83386. };
  83387. ;
  83388. return ShadowsOptimization;
  83389. }(SceneOptimization));
  83390. BABYLON.ShadowsOptimization = ShadowsOptimization;
  83391. /**
  83392. * Defines an optimization used to turn post-processes off
  83393. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83394. */
  83395. var PostProcessesOptimization = /** @class */ (function (_super) {
  83396. __extends(PostProcessesOptimization, _super);
  83397. function PostProcessesOptimization() {
  83398. return _super !== null && _super.apply(this, arguments) || this;
  83399. }
  83400. /**
  83401. * Gets a string describing the action executed by the current optimization
  83402. * @return description string
  83403. */
  83404. PostProcessesOptimization.prototype.getDescription = function () {
  83405. return "Turning post-processes on/off";
  83406. };
  83407. /**
  83408. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83409. * @param scene defines the current scene where to apply this optimization
  83410. * @param optimizer defines the current optimizer
  83411. * @returns true if everything that can be done was applied
  83412. */
  83413. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  83414. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  83415. return true;
  83416. };
  83417. ;
  83418. return PostProcessesOptimization;
  83419. }(SceneOptimization));
  83420. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  83421. /**
  83422. * Defines an optimization used to turn lens flares off
  83423. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83424. */
  83425. var LensFlaresOptimization = /** @class */ (function (_super) {
  83426. __extends(LensFlaresOptimization, _super);
  83427. function LensFlaresOptimization() {
  83428. return _super !== null && _super.apply(this, arguments) || this;
  83429. }
  83430. /**
  83431. * Gets a string describing the action executed by the current optimization
  83432. * @return description string
  83433. */
  83434. LensFlaresOptimization.prototype.getDescription = function () {
  83435. return "Turning lens flares on/off";
  83436. };
  83437. /**
  83438. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83439. * @param scene defines the current scene where to apply this optimization
  83440. * @param optimizer defines the current optimizer
  83441. * @returns true if everything that can be done was applied
  83442. */
  83443. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  83444. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  83445. return true;
  83446. };
  83447. ;
  83448. return LensFlaresOptimization;
  83449. }(SceneOptimization));
  83450. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  83451. /**
  83452. * Defines an optimization based on user defined callback.
  83453. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83454. */
  83455. var CustomOptimization = /** @class */ (function (_super) {
  83456. __extends(CustomOptimization, _super);
  83457. function CustomOptimization() {
  83458. return _super !== null && _super.apply(this, arguments) || this;
  83459. }
  83460. /**
  83461. * Gets a string describing the action executed by the current optimization
  83462. * @returns description string
  83463. */
  83464. CustomOptimization.prototype.getDescription = function () {
  83465. if (this.onGetDescription) {
  83466. return this.onGetDescription();
  83467. }
  83468. return "Running user defined callback";
  83469. };
  83470. /**
  83471. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83472. * @param scene defines the current scene where to apply this optimization
  83473. * @param optimizer defines the current optimizer
  83474. * @returns true if everything that can be done was applied
  83475. */
  83476. CustomOptimization.prototype.apply = function (scene, optimizer) {
  83477. if (this.onApply) {
  83478. return this.onApply(scene, optimizer);
  83479. }
  83480. return true;
  83481. };
  83482. ;
  83483. return CustomOptimization;
  83484. }(SceneOptimization));
  83485. BABYLON.CustomOptimization = CustomOptimization;
  83486. /**
  83487. * Defines an optimization used to turn particles off
  83488. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83489. */
  83490. var ParticlesOptimization = /** @class */ (function (_super) {
  83491. __extends(ParticlesOptimization, _super);
  83492. function ParticlesOptimization() {
  83493. return _super !== null && _super.apply(this, arguments) || this;
  83494. }
  83495. /**
  83496. * Gets a string describing the action executed by the current optimization
  83497. * @return description string
  83498. */
  83499. ParticlesOptimization.prototype.getDescription = function () {
  83500. return "Turning particles on/off";
  83501. };
  83502. /**
  83503. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83504. * @param scene defines the current scene where to apply this optimization
  83505. * @param optimizer defines the current optimizer
  83506. * @returns true if everything that can be done was applied
  83507. */
  83508. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  83509. scene.particlesEnabled = optimizer.isInImprovementMode;
  83510. return true;
  83511. };
  83512. ;
  83513. return ParticlesOptimization;
  83514. }(SceneOptimization));
  83515. BABYLON.ParticlesOptimization = ParticlesOptimization;
  83516. /**
  83517. * Defines an optimization used to turn render targets off
  83518. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83519. */
  83520. var RenderTargetsOptimization = /** @class */ (function (_super) {
  83521. __extends(RenderTargetsOptimization, _super);
  83522. function RenderTargetsOptimization() {
  83523. return _super !== null && _super.apply(this, arguments) || this;
  83524. }
  83525. /**
  83526. * Gets a string describing the action executed by the current optimization
  83527. * @return description string
  83528. */
  83529. RenderTargetsOptimization.prototype.getDescription = function () {
  83530. return "Turning render targets off";
  83531. };
  83532. /**
  83533. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83534. * @param scene defines the current scene where to apply this optimization
  83535. * @param optimizer defines the current optimizer
  83536. * @returns true if everything that can be done was applied
  83537. */
  83538. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  83539. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  83540. return true;
  83541. };
  83542. ;
  83543. return RenderTargetsOptimization;
  83544. }(SceneOptimization));
  83545. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  83546. /**
  83547. * Defines an optimization used to merge meshes with compatible materials
  83548. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83549. */
  83550. var MergeMeshesOptimization = /** @class */ (function (_super) {
  83551. __extends(MergeMeshesOptimization, _super);
  83552. function MergeMeshesOptimization() {
  83553. var _this = _super !== null && _super.apply(this, arguments) || this;
  83554. _this._canBeMerged = function (abstractMesh) {
  83555. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  83556. return false;
  83557. }
  83558. var mesh = abstractMesh;
  83559. if (!mesh.isVisible || !mesh.isEnabled()) {
  83560. return false;
  83561. }
  83562. if (mesh.instances.length > 0) {
  83563. return false;
  83564. }
  83565. if (mesh.skeleton || mesh.hasLODLevels) {
  83566. return false;
  83567. }
  83568. if (mesh.parent) {
  83569. return false;
  83570. }
  83571. return true;
  83572. };
  83573. return _this;
  83574. }
  83575. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  83576. /**
  83577. * Gets or sets a boolean which defines if optimization octree has to be updated
  83578. */
  83579. get: function () {
  83580. return MergeMeshesOptimization._UpdateSelectionTree;
  83581. },
  83582. /**
  83583. * Gets or sets a boolean which defines if optimization octree has to be updated
  83584. */
  83585. set: function (value) {
  83586. MergeMeshesOptimization._UpdateSelectionTree = value;
  83587. },
  83588. enumerable: true,
  83589. configurable: true
  83590. });
  83591. /**
  83592. * Gets a string describing the action executed by the current optimization
  83593. * @return description string
  83594. */
  83595. MergeMeshesOptimization.prototype.getDescription = function () {
  83596. return "Merging similar meshes together";
  83597. };
  83598. /**
  83599. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83600. * @param scene defines the current scene where to apply this optimization
  83601. * @param optimizer defines the current optimizer
  83602. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  83603. * @returns true if everything that can be done was applied
  83604. */
  83605. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  83606. var globalPool = scene.meshes.slice(0);
  83607. var globalLength = globalPool.length;
  83608. for (var index = 0; index < globalLength; index++) {
  83609. var currentPool = new Array();
  83610. var current = globalPool[index];
  83611. // Checks
  83612. if (!this._canBeMerged(current)) {
  83613. continue;
  83614. }
  83615. currentPool.push(current);
  83616. // Find compatible meshes
  83617. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  83618. var otherMesh = globalPool[subIndex];
  83619. if (!this._canBeMerged(otherMesh)) {
  83620. continue;
  83621. }
  83622. if (otherMesh.material !== current.material) {
  83623. continue;
  83624. }
  83625. if (otherMesh.checkCollisions !== current.checkCollisions) {
  83626. continue;
  83627. }
  83628. currentPool.push(otherMesh);
  83629. globalLength--;
  83630. globalPool.splice(subIndex, 1);
  83631. subIndex--;
  83632. }
  83633. if (currentPool.length < 2) {
  83634. continue;
  83635. }
  83636. // Merge meshes
  83637. BABYLON.Mesh.MergeMeshes(currentPool);
  83638. }
  83639. if (updateSelectionTree != undefined) {
  83640. if (updateSelectionTree) {
  83641. scene.createOrUpdateSelectionOctree();
  83642. }
  83643. }
  83644. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  83645. scene.createOrUpdateSelectionOctree();
  83646. }
  83647. return true;
  83648. };
  83649. ;
  83650. MergeMeshesOptimization._UpdateSelectionTree = false;
  83651. return MergeMeshesOptimization;
  83652. }(SceneOptimization));
  83653. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  83654. /**
  83655. * Defines a list of options used by SceneOptimizer
  83656. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83657. */
  83658. var SceneOptimizerOptions = /** @class */ (function () {
  83659. /**
  83660. * Creates a new list of options used by SceneOptimizer
  83661. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  83662. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  83663. */
  83664. function SceneOptimizerOptions(
  83665. /**
  83666. * Defines the target frame rate to reach (60 by default)
  83667. */
  83668. targetFrameRate,
  83669. /**
  83670. * Defines the interval between two checkes (2000ms by default)
  83671. */
  83672. trackerDuration) {
  83673. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  83674. if (trackerDuration === void 0) { trackerDuration = 2000; }
  83675. this.targetFrameRate = targetFrameRate;
  83676. this.trackerDuration = trackerDuration;
  83677. /**
  83678. * Gets the list of optimizations to apply
  83679. */
  83680. this.optimizations = new Array();
  83681. }
  83682. /**
  83683. * Add a new optimization
  83684. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  83685. * @returns the current SceneOptimizerOptions
  83686. */
  83687. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  83688. this.optimizations.push(optimization);
  83689. return this;
  83690. };
  83691. /**
  83692. * Add a new custom optimization
  83693. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  83694. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  83695. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83696. * @returns the current SceneOptimizerOptions
  83697. */
  83698. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  83699. if (priority === void 0) { priority = 0; }
  83700. var optimization = new CustomOptimization(priority);
  83701. optimization.onApply = onApply;
  83702. optimization.onGetDescription = onGetDescription;
  83703. this.optimizations.push(optimization);
  83704. return this;
  83705. };
  83706. /**
  83707. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  83708. * @param targetFrameRate defines the target frame rate (60 by default)
  83709. * @returns a SceneOptimizerOptions object
  83710. */
  83711. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  83712. var result = new SceneOptimizerOptions(targetFrameRate);
  83713. var priority = 0;
  83714. result.addOptimization(new MergeMeshesOptimization(priority));
  83715. result.addOptimization(new ShadowsOptimization(priority));
  83716. result.addOptimization(new LensFlaresOptimization(priority));
  83717. // Next priority
  83718. priority++;
  83719. result.addOptimization(new PostProcessesOptimization(priority));
  83720. result.addOptimization(new ParticlesOptimization(priority));
  83721. // Next priority
  83722. priority++;
  83723. result.addOptimization(new TextureOptimization(priority, 1024));
  83724. return result;
  83725. };
  83726. /**
  83727. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  83728. * @param targetFrameRate defines the target frame rate (60 by default)
  83729. * @returns a SceneOptimizerOptions object
  83730. */
  83731. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  83732. var result = new SceneOptimizerOptions(targetFrameRate);
  83733. var priority = 0;
  83734. result.addOptimization(new MergeMeshesOptimization(priority));
  83735. result.addOptimization(new ShadowsOptimization(priority));
  83736. result.addOptimization(new LensFlaresOptimization(priority));
  83737. // Next priority
  83738. priority++;
  83739. result.addOptimization(new PostProcessesOptimization(priority));
  83740. result.addOptimization(new ParticlesOptimization(priority));
  83741. // Next priority
  83742. priority++;
  83743. result.addOptimization(new TextureOptimization(priority, 512));
  83744. // Next priority
  83745. priority++;
  83746. result.addOptimization(new RenderTargetsOptimization(priority));
  83747. // Next priority
  83748. priority++;
  83749. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  83750. return result;
  83751. };
  83752. /**
  83753. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  83754. * @param targetFrameRate defines the target frame rate (60 by default)
  83755. * @returns a SceneOptimizerOptions object
  83756. */
  83757. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  83758. var result = new SceneOptimizerOptions(targetFrameRate);
  83759. var priority = 0;
  83760. result.addOptimization(new MergeMeshesOptimization(priority));
  83761. result.addOptimization(new ShadowsOptimization(priority));
  83762. result.addOptimization(new LensFlaresOptimization(priority));
  83763. // Next priority
  83764. priority++;
  83765. result.addOptimization(new PostProcessesOptimization(priority));
  83766. result.addOptimization(new ParticlesOptimization(priority));
  83767. // Next priority
  83768. priority++;
  83769. result.addOptimization(new TextureOptimization(priority, 256));
  83770. // Next priority
  83771. priority++;
  83772. result.addOptimization(new RenderTargetsOptimization(priority));
  83773. // Next priority
  83774. priority++;
  83775. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  83776. return result;
  83777. };
  83778. return SceneOptimizerOptions;
  83779. }());
  83780. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  83781. /**
  83782. * Class used to run optimizations in order to reach a target frame rate
  83783. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83784. */
  83785. var SceneOptimizer = /** @class */ (function () {
  83786. /**
  83787. * Creates a new SceneOptimizer
  83788. * @param scene defines the scene to work on
  83789. * @param options defines the options to use with the SceneOptimizer
  83790. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  83791. * @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)
  83792. */
  83793. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  83794. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  83795. if (improvementMode === void 0) { improvementMode = false; }
  83796. var _this = this;
  83797. this._isRunning = false;
  83798. this._currentPriorityLevel = 0;
  83799. this._targetFrameRate = 60;
  83800. this._trackerDuration = 2000;
  83801. this._currentFrameRate = 0;
  83802. this._improvementMode = false;
  83803. /**
  83804. * Defines an observable called when the optimizer reaches the target frame rate
  83805. */
  83806. this.onSuccessObservable = new BABYLON.Observable();
  83807. /**
  83808. * Defines an observable called when the optimizer enables an optimization
  83809. */
  83810. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  83811. /**
  83812. * Defines an observable called when the optimizer is not able to reach the target frame rate
  83813. */
  83814. this.onFailureObservable = new BABYLON.Observable();
  83815. if (!options) {
  83816. this._options = new SceneOptimizerOptions();
  83817. }
  83818. else {
  83819. this._options = options;
  83820. }
  83821. if (this._options.targetFrameRate) {
  83822. this._targetFrameRate = this._options.targetFrameRate;
  83823. }
  83824. if (this._options.trackerDuration) {
  83825. this._trackerDuration = this._options.trackerDuration;
  83826. }
  83827. if (autoGeneratePriorities) {
  83828. var priority = 0;
  83829. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  83830. var optim = _a[_i];
  83831. optim.priority = priority++;
  83832. }
  83833. }
  83834. this._improvementMode = improvementMode;
  83835. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83836. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  83837. _this._sceneDisposeObserver = null;
  83838. _this.dispose();
  83839. });
  83840. }
  83841. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  83842. /**
  83843. * Gets a boolean indicating if the optimizer is in improvement mode
  83844. */
  83845. get: function () {
  83846. return this._improvementMode;
  83847. },
  83848. enumerable: true,
  83849. configurable: true
  83850. });
  83851. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  83852. /**
  83853. * Gets the current priority level (0 at start)
  83854. */
  83855. get: function () {
  83856. return this._currentPriorityLevel;
  83857. },
  83858. enumerable: true,
  83859. configurable: true
  83860. });
  83861. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  83862. /**
  83863. * Gets the current frame rate checked by the SceneOptimizer
  83864. */
  83865. get: function () {
  83866. return this._currentFrameRate;
  83867. },
  83868. enumerable: true,
  83869. configurable: true
  83870. });
  83871. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  83872. /**
  83873. * Gets or sets the current target frame rate (60 by default)
  83874. */
  83875. get: function () {
  83876. return this._targetFrameRate;
  83877. },
  83878. /**
  83879. * Gets or sets the current target frame rate (60 by default)
  83880. */
  83881. set: function (value) {
  83882. this._targetFrameRate = value;
  83883. },
  83884. enumerable: true,
  83885. configurable: true
  83886. });
  83887. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  83888. /**
  83889. * Gets or sets the current interval between two checks (every 2000ms by default)
  83890. */
  83891. get: function () {
  83892. return this._trackerDuration;
  83893. },
  83894. /**
  83895. * Gets or sets the current interval between two checks (every 2000ms by default)
  83896. */
  83897. set: function (value) {
  83898. this._trackerDuration = value;
  83899. },
  83900. enumerable: true,
  83901. configurable: true
  83902. });
  83903. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  83904. /**
  83905. * Gets the list of active optimizations
  83906. */
  83907. get: function () {
  83908. return this._options.optimizations;
  83909. },
  83910. enumerable: true,
  83911. configurable: true
  83912. });
  83913. /**
  83914. * Stops the current optimizer
  83915. */
  83916. SceneOptimizer.prototype.stop = function () {
  83917. this._isRunning = false;
  83918. };
  83919. /**
  83920. * Reset the optimizer to initial step (current priority level = 0)
  83921. */
  83922. SceneOptimizer.prototype.reset = function () {
  83923. this._currentPriorityLevel = 0;
  83924. };
  83925. /**
  83926. * Start the optimizer. By default it will try to reach a specific framerate
  83927. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  83928. */
  83929. SceneOptimizer.prototype.start = function () {
  83930. var _this = this;
  83931. if (this._isRunning) {
  83932. return;
  83933. }
  83934. this._isRunning = true;
  83935. // Let's wait for the scene to be ready before running our check
  83936. this._scene.executeWhenReady(function () {
  83937. setTimeout(function () {
  83938. _this._checkCurrentState();
  83939. }, _this._trackerDuration);
  83940. });
  83941. };
  83942. SceneOptimizer.prototype._checkCurrentState = function () {
  83943. var _this = this;
  83944. if (!this._isRunning) {
  83945. return;
  83946. }
  83947. var scene = this._scene;
  83948. var options = this._options;
  83949. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  83950. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  83951. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  83952. this._isRunning = false;
  83953. this.onSuccessObservable.notifyObservers(this);
  83954. return;
  83955. }
  83956. // Apply current level of optimizations
  83957. var allDone = true;
  83958. var noOptimizationApplied = true;
  83959. for (var index = 0; index < options.optimizations.length; index++) {
  83960. var optimization = options.optimizations[index];
  83961. if (optimization.priority === this._currentPriorityLevel) {
  83962. noOptimizationApplied = false;
  83963. allDone = allDone && optimization.apply(scene, this);
  83964. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  83965. }
  83966. }
  83967. // If no optimization was applied, this is a failure :(
  83968. if (noOptimizationApplied) {
  83969. this._isRunning = false;
  83970. this.onFailureObservable.notifyObservers(this);
  83971. return;
  83972. }
  83973. // If all optimizations were done, move to next level
  83974. if (allDone) {
  83975. this._currentPriorityLevel++;
  83976. }
  83977. // Let's the system running for a specific amount of time before checking FPS
  83978. scene.executeWhenReady(function () {
  83979. setTimeout(function () {
  83980. _this._checkCurrentState();
  83981. }, _this._trackerDuration);
  83982. });
  83983. };
  83984. /**
  83985. * Release all resources
  83986. */
  83987. SceneOptimizer.prototype.dispose = function () {
  83988. this.stop();
  83989. this.onSuccessObservable.clear();
  83990. this.onFailureObservable.clear();
  83991. this.onNewOptimizationAppliedObservable.clear();
  83992. if (this._sceneDisposeObserver) {
  83993. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  83994. }
  83995. };
  83996. /**
  83997. * Helper function to create a SceneOptimizer with one single line of code
  83998. * @param scene defines the scene to work on
  83999. * @param options defines the options to use with the SceneOptimizer
  84000. * @param onSuccess defines a callback to call on success
  84001. * @param onFailure defines a callback to call on failure
  84002. * @returns the new SceneOptimizer object
  84003. */
  84004. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  84005. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  84006. if (onSuccess) {
  84007. optimizer.onSuccessObservable.add(function () {
  84008. onSuccess();
  84009. });
  84010. }
  84011. if (onFailure) {
  84012. optimizer.onFailureObservable.add(function () {
  84013. onFailure();
  84014. });
  84015. }
  84016. optimizer.start();
  84017. return optimizer;
  84018. };
  84019. return SceneOptimizer;
  84020. }());
  84021. BABYLON.SceneOptimizer = SceneOptimizer;
  84022. })(BABYLON || (BABYLON = {}));
  84023. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  84024. var BABYLON;
  84025. (function (BABYLON) {
  84026. var OutlineRenderer = /** @class */ (function () {
  84027. function OutlineRenderer(scene) {
  84028. this.zOffset = 1;
  84029. this._scene = scene;
  84030. }
  84031. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  84032. var _this = this;
  84033. if (useOverlay === void 0) { useOverlay = false; }
  84034. var scene = this._scene;
  84035. var engine = this._scene.getEngine();
  84036. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84037. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  84038. return;
  84039. }
  84040. var mesh = subMesh.getRenderingMesh();
  84041. var material = subMesh.getMaterial();
  84042. if (!material || !scene.activeCamera) {
  84043. return;
  84044. }
  84045. engine.enableEffect(this._effect);
  84046. // Logarithmic depth
  84047. if (material.useLogarithmicDepth) {
  84048. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  84049. }
  84050. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  84051. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  84052. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84053. // Bones
  84054. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84055. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84056. }
  84057. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  84058. // Alpha test
  84059. if (material && material.needAlphaTesting()) {
  84060. var alphaTexture = material.getAlphaTestTexture();
  84061. if (alphaTexture) {
  84062. this._effect.setTexture("diffuseSampler", alphaTexture);
  84063. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84064. }
  84065. }
  84066. engine.setZOffset(-this.zOffset);
  84067. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  84068. engine.setZOffset(0);
  84069. };
  84070. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  84071. var defines = [];
  84072. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  84073. var mesh = subMesh.getMesh();
  84074. var material = subMesh.getMaterial();
  84075. if (material) {
  84076. // Alpha test
  84077. if (material.needAlphaTesting()) {
  84078. defines.push("#define ALPHATEST");
  84079. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84080. attribs.push(BABYLON.VertexBuffer.UVKind);
  84081. defines.push("#define UV1");
  84082. }
  84083. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84084. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84085. defines.push("#define UV2");
  84086. }
  84087. }
  84088. //Logarithmic depth
  84089. if (material.useLogarithmicDepth) {
  84090. defines.push("#define LOGARITHMICDEPTH");
  84091. }
  84092. }
  84093. // Bones
  84094. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84095. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84096. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84097. if (mesh.numBoneInfluencers > 4) {
  84098. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84099. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84100. }
  84101. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84102. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84103. }
  84104. else {
  84105. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84106. }
  84107. // Instances
  84108. if (useInstances) {
  84109. defines.push("#define INSTANCES");
  84110. attribs.push("world0");
  84111. attribs.push("world1");
  84112. attribs.push("world2");
  84113. attribs.push("world3");
  84114. }
  84115. // Get correct effect
  84116. var join = defines.join("\n");
  84117. if (this._cachedDefines !== join) {
  84118. this._cachedDefines = join;
  84119. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  84120. }
  84121. return this._effect.isReady();
  84122. };
  84123. return OutlineRenderer;
  84124. }());
  84125. BABYLON.OutlineRenderer = OutlineRenderer;
  84126. })(BABYLON || (BABYLON = {}));
  84127. //# sourceMappingURL=babylon.outlineRenderer.js.map
  84128. var BABYLON;
  84129. (function (BABYLON) {
  84130. var FaceAdjacencies = /** @class */ (function () {
  84131. function FaceAdjacencies() {
  84132. this.edges = new Array();
  84133. this.edgesConnectedCount = 0;
  84134. }
  84135. return FaceAdjacencies;
  84136. }());
  84137. var EdgesRenderer = /** @class */ (function () {
  84138. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  84139. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  84140. if (epsilon === void 0) { epsilon = 0.95; }
  84141. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  84142. this.edgesWidthScalerForOrthographic = 1000.0;
  84143. this.edgesWidthScalerForPerspective = 50.0;
  84144. this._linesPositions = new Array();
  84145. this._linesNormals = new Array();
  84146. this._linesIndices = new Array();
  84147. this._buffers = {};
  84148. this._checkVerticesInsteadOfIndices = false;
  84149. this._source = source;
  84150. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  84151. this._epsilon = epsilon;
  84152. this._prepareRessources();
  84153. this._generateEdgesLines();
  84154. }
  84155. EdgesRenderer.prototype._prepareRessources = function () {
  84156. if (this._lineShader) {
  84157. return;
  84158. }
  84159. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  84160. attributes: ["position", "normal"],
  84161. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  84162. });
  84163. this._lineShader.disableDepthWrite = true;
  84164. this._lineShader.backFaceCulling = false;
  84165. };
  84166. EdgesRenderer.prototype._rebuild = function () {
  84167. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84168. if (buffer) {
  84169. buffer._rebuild();
  84170. }
  84171. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84172. if (buffer) {
  84173. buffer._rebuild();
  84174. }
  84175. var scene = this._source.getScene();
  84176. var engine = scene.getEngine();
  84177. this._ib = engine.createIndexBuffer(this._linesIndices);
  84178. };
  84179. EdgesRenderer.prototype.dispose = function () {
  84180. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84181. if (buffer) {
  84182. buffer.dispose();
  84183. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  84184. }
  84185. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84186. if (buffer) {
  84187. buffer.dispose();
  84188. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  84189. }
  84190. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  84191. this._lineShader.dispose();
  84192. };
  84193. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  84194. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  84195. return 0;
  84196. }
  84197. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  84198. return 1;
  84199. }
  84200. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  84201. return 2;
  84202. }
  84203. return -1;
  84204. };
  84205. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  84206. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  84207. return 0;
  84208. }
  84209. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  84210. return 1;
  84211. }
  84212. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  84213. return 2;
  84214. }
  84215. return -1;
  84216. };
  84217. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  84218. var needToCreateLine;
  84219. if (edge === undefined) {
  84220. needToCreateLine = true;
  84221. }
  84222. else {
  84223. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  84224. needToCreateLine = dotProduct < this._epsilon;
  84225. }
  84226. if (needToCreateLine) {
  84227. var offset = this._linesPositions.length / 3;
  84228. var normal = p0.subtract(p1);
  84229. normal.normalize();
  84230. // Positions
  84231. this._linesPositions.push(p0.x);
  84232. this._linesPositions.push(p0.y);
  84233. this._linesPositions.push(p0.z);
  84234. this._linesPositions.push(p0.x);
  84235. this._linesPositions.push(p0.y);
  84236. this._linesPositions.push(p0.z);
  84237. this._linesPositions.push(p1.x);
  84238. this._linesPositions.push(p1.y);
  84239. this._linesPositions.push(p1.z);
  84240. this._linesPositions.push(p1.x);
  84241. this._linesPositions.push(p1.y);
  84242. this._linesPositions.push(p1.z);
  84243. // Normals
  84244. this._linesNormals.push(p1.x);
  84245. this._linesNormals.push(p1.y);
  84246. this._linesNormals.push(p1.z);
  84247. this._linesNormals.push(-1);
  84248. this._linesNormals.push(p1.x);
  84249. this._linesNormals.push(p1.y);
  84250. this._linesNormals.push(p1.z);
  84251. this._linesNormals.push(1);
  84252. this._linesNormals.push(p0.x);
  84253. this._linesNormals.push(p0.y);
  84254. this._linesNormals.push(p0.z);
  84255. this._linesNormals.push(-1);
  84256. this._linesNormals.push(p0.x);
  84257. this._linesNormals.push(p0.y);
  84258. this._linesNormals.push(p0.z);
  84259. this._linesNormals.push(1);
  84260. // Indices
  84261. this._linesIndices.push(offset);
  84262. this._linesIndices.push(offset + 1);
  84263. this._linesIndices.push(offset + 2);
  84264. this._linesIndices.push(offset);
  84265. this._linesIndices.push(offset + 2);
  84266. this._linesIndices.push(offset + 3);
  84267. }
  84268. };
  84269. EdgesRenderer.prototype._generateEdgesLines = function () {
  84270. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84271. var indices = this._source.getIndices();
  84272. if (!indices || !positions) {
  84273. return;
  84274. }
  84275. // First let's find adjacencies
  84276. var adjacencies = new Array();
  84277. var faceNormals = new Array();
  84278. var index;
  84279. var faceAdjacencies;
  84280. // Prepare faces
  84281. for (index = 0; index < indices.length; index += 3) {
  84282. faceAdjacencies = new FaceAdjacencies();
  84283. var p0Index = indices[index];
  84284. var p1Index = indices[index + 1];
  84285. var p2Index = indices[index + 2];
  84286. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  84287. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  84288. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  84289. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  84290. faceNormal.normalize();
  84291. faceNormals.push(faceNormal);
  84292. adjacencies.push(faceAdjacencies);
  84293. }
  84294. // Scan
  84295. for (index = 0; index < adjacencies.length; index++) {
  84296. faceAdjacencies = adjacencies[index];
  84297. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  84298. var otherFaceAdjacencies = adjacencies[otherIndex];
  84299. if (faceAdjacencies.edgesConnectedCount === 3) {
  84300. break;
  84301. }
  84302. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  84303. continue;
  84304. }
  84305. var otherP0 = indices[otherIndex * 3];
  84306. var otherP1 = indices[otherIndex * 3 + 1];
  84307. var otherP2 = indices[otherIndex * 3 + 2];
  84308. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  84309. var otherEdgeIndex = 0;
  84310. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  84311. continue;
  84312. }
  84313. switch (edgeIndex) {
  84314. case 0:
  84315. if (this._checkVerticesInsteadOfIndices) {
  84316. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84317. }
  84318. else {
  84319. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  84320. }
  84321. break;
  84322. case 1:
  84323. if (this._checkVerticesInsteadOfIndices) {
  84324. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84325. }
  84326. else {
  84327. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  84328. }
  84329. break;
  84330. case 2:
  84331. if (this._checkVerticesInsteadOfIndices) {
  84332. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  84333. }
  84334. else {
  84335. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  84336. }
  84337. break;
  84338. }
  84339. if (otherEdgeIndex === -1) {
  84340. continue;
  84341. }
  84342. faceAdjacencies.edges[edgeIndex] = otherIndex;
  84343. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  84344. faceAdjacencies.edgesConnectedCount++;
  84345. otherFaceAdjacencies.edgesConnectedCount++;
  84346. if (faceAdjacencies.edgesConnectedCount === 3) {
  84347. break;
  84348. }
  84349. }
  84350. }
  84351. }
  84352. // Create lines
  84353. for (index = 0; index < adjacencies.length; index++) {
  84354. // 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
  84355. var current = adjacencies[index];
  84356. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  84357. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  84358. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  84359. }
  84360. // Merge into a single mesh
  84361. var engine = this._source.getScene().getEngine();
  84362. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  84363. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  84364. this._ib = engine.createIndexBuffer(this._linesIndices);
  84365. this._indicesCount = this._linesIndices.length;
  84366. };
  84367. EdgesRenderer.prototype.render = function () {
  84368. var scene = this._source.getScene();
  84369. if (!this._lineShader.isReady() || !scene.activeCamera) {
  84370. return;
  84371. }
  84372. var engine = scene.getEngine();
  84373. this._lineShader._preBind();
  84374. // VBOs
  84375. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  84376. scene.resetCachedMaterial();
  84377. this._lineShader.setColor4("color", this._source.edgesColor);
  84378. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  84379. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  84380. }
  84381. else {
  84382. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  84383. }
  84384. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  84385. this._lineShader.bind(this._source.getWorldMatrix());
  84386. // Draw order
  84387. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  84388. this._lineShader.unbind();
  84389. engine.setDepthWrite(true);
  84390. };
  84391. return EdgesRenderer;
  84392. }());
  84393. BABYLON.EdgesRenderer = EdgesRenderer;
  84394. })(BABYLON || (BABYLON = {}));
  84395. //# sourceMappingURL=babylon.edgesRenderer.js.map
  84396. var __assign = (this && this.__assign) || Object.assign || function(t) {
  84397. for (var s, i = 1, n = arguments.length; i < n; i++) {
  84398. s = arguments[i];
  84399. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  84400. t[p] = s[p];
  84401. }
  84402. return t;
  84403. };
  84404. var BABYLON;
  84405. (function (BABYLON) {
  84406. /**
  84407. * The effect layer Helps adding post process effect blended with the main pass.
  84408. *
  84409. * This can be for instance use to generate glow or higlight effects on the scene.
  84410. *
  84411. * The effect layer class can not be used directly and is intented to inherited from to be
  84412. * customized per effects.
  84413. */
  84414. var EffectLayer = /** @class */ (function () {
  84415. /**
  84416. * Instantiates a new effect Layer and references it in the scene.
  84417. * @param name The name of the layer
  84418. * @param scene The scene to use the layer in
  84419. */
  84420. function EffectLayer(
  84421. /** The Friendly of the effect in the scene */
  84422. name, scene) {
  84423. this.name = name;
  84424. this._vertexBuffers = {};
  84425. this._maxSize = 0;
  84426. this._mainTextureDesiredSize = { width: 0, height: 0 };
  84427. this._shouldRender = true;
  84428. this._postProcesses = [];
  84429. this._textures = [];
  84430. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  84431. /**
  84432. * The clear color of the texture used to generate the glow map.
  84433. */
  84434. this.neutralColor = new BABYLON.Color4();
  84435. /**
  84436. * Specifies wether the highlight layer is enabled or not.
  84437. */
  84438. this.isEnabled = true;
  84439. /**
  84440. * An event triggered when the effect layer has been disposed.
  84441. */
  84442. this.onDisposeObservable = new BABYLON.Observable();
  84443. /**
  84444. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  84445. */
  84446. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  84447. /**
  84448. * An event triggered when the generated texture is being merged in the scene.
  84449. */
  84450. this.onBeforeComposeObservable = new BABYLON.Observable();
  84451. /**
  84452. * An event triggered when the generated texture has been merged in the scene.
  84453. */
  84454. this.onAfterComposeObservable = new BABYLON.Observable();
  84455. /**
  84456. * An event triggered when the efffect layer changes its size.
  84457. */
  84458. this.onSizeChangedObservable = new BABYLON.Observable();
  84459. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84460. this._engine = scene.getEngine();
  84461. this._maxSize = this._engine.getCaps().maxTextureSize;
  84462. this._scene.effectLayers.push(this);
  84463. // Generate Buffers
  84464. this._generateIndexBuffer();
  84465. this._genrateVertexBuffer();
  84466. }
  84467. Object.defineProperty(EffectLayer.prototype, "camera", {
  84468. /**
  84469. * Gets the camera attached to the layer.
  84470. */
  84471. get: function () {
  84472. return this._effectLayerOptions.camera;
  84473. },
  84474. enumerable: true,
  84475. configurable: true
  84476. });
  84477. /**
  84478. * Initializes the effect layer with the required options.
  84479. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  84480. */
  84481. EffectLayer.prototype._init = function (options) {
  84482. // Adapt options
  84483. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84484. this._setMainTextureSize();
  84485. this._createMainTexture();
  84486. this._createTextureAndPostProcesses();
  84487. this._mergeEffect = this._createMergeEffect();
  84488. };
  84489. /**
  84490. * Generates the index buffer of the full screen quad blending to the main canvas.
  84491. */
  84492. EffectLayer.prototype._generateIndexBuffer = function () {
  84493. // Indices
  84494. var indices = [];
  84495. indices.push(0);
  84496. indices.push(1);
  84497. indices.push(2);
  84498. indices.push(0);
  84499. indices.push(2);
  84500. indices.push(3);
  84501. this._indexBuffer = this._engine.createIndexBuffer(indices);
  84502. };
  84503. /**
  84504. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  84505. */
  84506. EffectLayer.prototype._genrateVertexBuffer = function () {
  84507. // VBO
  84508. var vertices = [];
  84509. vertices.push(1, 1);
  84510. vertices.push(-1, 1);
  84511. vertices.push(-1, -1);
  84512. vertices.push(1, -1);
  84513. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84514. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84515. };
  84516. /**
  84517. * Sets the main texture desired size which is the closest power of two
  84518. * of the engine canvas size.
  84519. */
  84520. EffectLayer.prototype._setMainTextureSize = function () {
  84521. if (this._effectLayerOptions.mainTextureFixedSize) {
  84522. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  84523. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  84524. }
  84525. else {
  84526. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  84527. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  84528. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  84529. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  84530. }
  84531. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  84532. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  84533. };
  84534. /**
  84535. * Creates the main texture for the effect layer.
  84536. */
  84537. EffectLayer.prototype._createMainTexture = function () {
  84538. var _this = this;
  84539. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  84540. width: this._mainTextureDesiredSize.width,
  84541. height: this._mainTextureDesiredSize.height
  84542. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84543. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  84544. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84545. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84546. this._mainTexture.anisotropicFilteringLevel = 1;
  84547. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84548. this._mainTexture.renderParticles = false;
  84549. this._mainTexture.renderList = null;
  84550. this._mainTexture.ignoreCameraViewport = true;
  84551. // Custom render function
  84552. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84553. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  84554. var index;
  84555. var engine = _this._scene.getEngine();
  84556. if (depthOnlySubMeshes.length) {
  84557. engine.setColorWrite(false);
  84558. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84559. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  84560. }
  84561. engine.setColorWrite(true);
  84562. }
  84563. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84564. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  84565. }
  84566. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84567. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  84568. }
  84569. for (index = 0; index < transparentSubMeshes.length; index++) {
  84570. _this._renderSubMesh(transparentSubMeshes.data[index]);
  84571. }
  84572. };
  84573. this._mainTexture.onClearObservable.add(function (engine) {
  84574. engine.clear(_this.neutralColor, true, true, true);
  84575. });
  84576. };
  84577. /**
  84578. * Checks for the readiness of the element composing the layer.
  84579. * @param subMesh the mesh to check for
  84580. * @param useInstances specify wether or not to use instances to render the mesh
  84581. * @param emissiveTexture the associated emissive texture used to generate the glow
  84582. * @return true if ready otherwise, false
  84583. */
  84584. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  84585. var material = subMesh.getMaterial();
  84586. if (!material) {
  84587. return false;
  84588. }
  84589. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  84590. return false;
  84591. }
  84592. var defines = [];
  84593. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84594. var mesh = subMesh.getMesh();
  84595. var uv1 = false;
  84596. var uv2 = false;
  84597. // Alpha test
  84598. if (material && material.needAlphaTesting()) {
  84599. var alphaTexture = material.getAlphaTestTexture();
  84600. if (alphaTexture) {
  84601. defines.push("#define ALPHATEST");
  84602. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84603. alphaTexture.coordinatesIndex === 1) {
  84604. defines.push("#define DIFFUSEUV2");
  84605. uv2 = true;
  84606. }
  84607. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84608. defines.push("#define DIFFUSEUV1");
  84609. uv1 = true;
  84610. }
  84611. }
  84612. }
  84613. // Emissive
  84614. if (emissiveTexture) {
  84615. defines.push("#define EMISSIVE");
  84616. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84617. emissiveTexture.coordinatesIndex === 1) {
  84618. defines.push("#define EMISSIVEUV2");
  84619. uv2 = true;
  84620. }
  84621. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84622. defines.push("#define EMISSIVEUV1");
  84623. uv1 = true;
  84624. }
  84625. }
  84626. if (uv1) {
  84627. attribs.push(BABYLON.VertexBuffer.UVKind);
  84628. defines.push("#define UV1");
  84629. }
  84630. if (uv2) {
  84631. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84632. defines.push("#define UV2");
  84633. }
  84634. // Bones
  84635. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84636. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84637. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84638. if (mesh.numBoneInfluencers > 4) {
  84639. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84640. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84641. }
  84642. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84643. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  84644. }
  84645. else {
  84646. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84647. }
  84648. // Instances
  84649. if (useInstances) {
  84650. defines.push("#define INSTANCES");
  84651. attribs.push("world0");
  84652. attribs.push("world1");
  84653. attribs.push("world2");
  84654. attribs.push("world3");
  84655. }
  84656. // Get correct effect
  84657. var join = defines.join("\n");
  84658. if (this._cachedDefines !== join) {
  84659. this._cachedDefines = join;
  84660. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  84661. }
  84662. return this._effectLayerMapGenerationEffect.isReady();
  84663. };
  84664. /**
  84665. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  84666. */
  84667. EffectLayer.prototype.render = function () {
  84668. var currentEffect = this._mergeEffect;
  84669. // Check
  84670. if (!currentEffect.isReady())
  84671. return;
  84672. for (var i = 0; i < this._postProcesses.length; i++) {
  84673. if (!this._postProcesses[i].isReady()) {
  84674. return;
  84675. }
  84676. }
  84677. var engine = this._scene.getEngine();
  84678. this.onBeforeComposeObservable.notifyObservers(this);
  84679. // Render
  84680. engine.enableEffect(currentEffect);
  84681. engine.setState(false);
  84682. // VBOs
  84683. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84684. // Cache
  84685. var previousAlphaMode = engine.getAlphaMode();
  84686. // Go Blend.
  84687. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  84688. // Blends the map on the main canvas.
  84689. this._internalRender(currentEffect);
  84690. // Restore Alpha
  84691. engine.setAlphaMode(previousAlphaMode);
  84692. this.onAfterComposeObservable.notifyObservers(this);
  84693. // Handle size changes.
  84694. var size = this._mainTexture.getSize();
  84695. this._setMainTextureSize();
  84696. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  84697. // Recreate RTT and post processes on size change.
  84698. this.onSizeChangedObservable.notifyObservers(this);
  84699. this._disposeTextureAndPostProcesses();
  84700. this._createMainTexture();
  84701. this._createTextureAndPostProcesses();
  84702. }
  84703. };
  84704. /**
  84705. * Determine if a given mesh will be used in the current effect.
  84706. * @param mesh mesh to test
  84707. * @returns true if the mesh will be used
  84708. */
  84709. EffectLayer.prototype.hasMesh = function (mesh) {
  84710. return true;
  84711. };
  84712. /**
  84713. * Returns true if the layer contains information to display, otherwise false.
  84714. * @returns true if the glow layer should be rendered
  84715. */
  84716. EffectLayer.prototype.shouldRender = function () {
  84717. return this.isEnabled && this._shouldRender;
  84718. };
  84719. /**
  84720. * Returns true if the mesh should render, otherwise false.
  84721. * @param mesh The mesh to render
  84722. * @returns true if it should render otherwise false
  84723. */
  84724. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  84725. return true;
  84726. };
  84727. /**
  84728. * Returns true if the mesh should render, otherwise false.
  84729. * @param mesh The mesh to render
  84730. * @returns true if it should render otherwise false
  84731. */
  84732. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  84733. return true;
  84734. };
  84735. /**
  84736. * Renders the submesh passed in parameter to the generation map.
  84737. */
  84738. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  84739. var _this = this;
  84740. if (!this.shouldRender()) {
  84741. return;
  84742. }
  84743. var material = subMesh.getMaterial();
  84744. var mesh = subMesh.getRenderingMesh();
  84745. var scene = this._scene;
  84746. var engine = scene.getEngine();
  84747. if (!material) {
  84748. return;
  84749. }
  84750. // Do not block in blend mode.
  84751. if (material.needAlphaBlendingForMesh(mesh)) {
  84752. return;
  84753. }
  84754. // Culling
  84755. engine.setState(material.backFaceCulling);
  84756. // Managing instances
  84757. var batch = mesh._getInstancesRenderList(subMesh._id);
  84758. if (batch.mustReturn) {
  84759. return;
  84760. }
  84761. // Early Exit per mesh
  84762. if (!this._shouldRenderMesh(mesh)) {
  84763. return;
  84764. }
  84765. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84766. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  84767. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  84768. engine.enableEffect(this._effectLayerMapGenerationEffect);
  84769. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  84770. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  84771. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  84772. // Alpha test
  84773. if (material && material.needAlphaTesting()) {
  84774. var alphaTexture = material.getAlphaTestTexture();
  84775. if (alphaTexture) {
  84776. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  84777. var textureMatrix = alphaTexture.getTextureMatrix();
  84778. if (textureMatrix) {
  84779. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  84780. }
  84781. }
  84782. }
  84783. // Glow emissive only
  84784. if (this._emissiveTextureAndColor.texture) {
  84785. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  84786. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  84787. }
  84788. // Bones
  84789. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84790. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84791. }
  84792. // Draw
  84793. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  84794. }
  84795. else {
  84796. // Need to reset refresh rate of the shadowMap
  84797. this._mainTexture.resetRefreshCounter();
  84798. }
  84799. };
  84800. /**
  84801. * Rebuild the required buffers.
  84802. * @ignore Internal use only.
  84803. */
  84804. EffectLayer.prototype._rebuild = function () {
  84805. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84806. if (vb) {
  84807. vb._rebuild();
  84808. }
  84809. this._generateIndexBuffer();
  84810. };
  84811. /**
  84812. * Dispose only the render target textures and post process.
  84813. */
  84814. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  84815. this._mainTexture.dispose();
  84816. for (var i = 0; i < this._postProcesses.length; i++) {
  84817. if (this._postProcesses[i]) {
  84818. this._postProcesses[i].dispose();
  84819. }
  84820. }
  84821. this._postProcesses = [];
  84822. for (var i = 0; i < this._textures.length; i++) {
  84823. if (this._textures[i]) {
  84824. this._textures[i].dispose();
  84825. }
  84826. }
  84827. this._textures = [];
  84828. };
  84829. /**
  84830. * Dispose the highlight layer and free resources.
  84831. */
  84832. EffectLayer.prototype.dispose = function () {
  84833. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84834. if (vertexBuffer) {
  84835. vertexBuffer.dispose();
  84836. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84837. }
  84838. if (this._indexBuffer) {
  84839. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84840. this._indexBuffer = null;
  84841. }
  84842. // Clean textures and post processes
  84843. this._disposeTextureAndPostProcesses();
  84844. // Remove from scene
  84845. var index = this._scene.effectLayers.indexOf(this, 0);
  84846. if (index > -1) {
  84847. this._scene.effectLayers.splice(index, 1);
  84848. }
  84849. // Callback
  84850. this.onDisposeObservable.notifyObservers(this);
  84851. this.onDisposeObservable.clear();
  84852. this.onBeforeRenderMainTextureObservable.clear();
  84853. this.onBeforeComposeObservable.clear();
  84854. this.onAfterComposeObservable.clear();
  84855. this.onSizeChangedObservable.clear();
  84856. };
  84857. return EffectLayer;
  84858. }());
  84859. BABYLON.EffectLayer = EffectLayer;
  84860. })(BABYLON || (BABYLON = {}));
  84861. //# sourceMappingURL=babylon.effectLayer.js.map
  84862. var BABYLON;
  84863. (function (BABYLON) {
  84864. /**
  84865. * Special Glow Blur post process only blurring the alpha channel
  84866. * It enforces keeping the most luminous color in the color channel.
  84867. */
  84868. var GlowBlurPostProcess = /** @class */ (function (_super) {
  84869. __extends(GlowBlurPostProcess, _super);
  84870. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  84871. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84872. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  84873. _this.direction = direction;
  84874. _this.kernel = kernel;
  84875. _this.onApplyObservable.add(function (effect) {
  84876. effect.setFloat2("screenSize", _this.width, _this.height);
  84877. effect.setVector2("direction", _this.direction);
  84878. effect.setFloat("blurWidth", _this.kernel);
  84879. });
  84880. return _this;
  84881. }
  84882. return GlowBlurPostProcess;
  84883. }(BABYLON.PostProcess));
  84884. /**
  84885. * The highlight layer Helps adding a glow effect around a mesh.
  84886. *
  84887. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84888. * glowy meshes to your scene.
  84889. *
  84890. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  84891. */
  84892. var HighlightLayer = /** @class */ (function (_super) {
  84893. __extends(HighlightLayer, _super);
  84894. /**
  84895. * Instantiates a new highlight Layer and references it to the scene..
  84896. * @param name The name of the layer
  84897. * @param scene The scene to use the layer in
  84898. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  84899. */
  84900. function HighlightLayer(name, scene, options) {
  84901. var _this = _super.call(this, name, scene) || this;
  84902. _this.name = name;
  84903. /**
  84904. * Specifies whether or not the inner glow is ACTIVE in the layer.
  84905. */
  84906. _this.innerGlow = true;
  84907. /**
  84908. * Specifies whether or not the outer glow is ACTIVE in the layer.
  84909. */
  84910. _this.outerGlow = true;
  84911. /**
  84912. * An event triggered when the highlight layer is being blurred.
  84913. */
  84914. _this.onBeforeBlurObservable = new BABYLON.Observable();
  84915. /**
  84916. * An event triggered when the highlight layer has been blurred.
  84917. */
  84918. _this.onAfterBlurObservable = new BABYLON.Observable();
  84919. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  84920. _this._meshes = {};
  84921. _this._excludedMeshes = {};
  84922. _this.neutralColor = HighlightLayer.NeutralColor;
  84923. // Warn on stencil
  84924. if (!_this._engine.isStencilEnable) {
  84925. 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 }");
  84926. }
  84927. // Adapt options
  84928. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84929. // Initialize the layer
  84930. _this._init({
  84931. alphaBlendingMode: _this._options.alphaBlendingMode,
  84932. camera: _this._options.camera,
  84933. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84934. mainTextureRatio: _this._options.mainTextureRatio
  84935. });
  84936. // Do not render as long as no meshes have been added
  84937. _this._shouldRender = false;
  84938. return _this;
  84939. }
  84940. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  84941. /**
  84942. * Gets the horizontal size of the blur.
  84943. */
  84944. get: function () {
  84945. return this._horizontalBlurPostprocess.kernel;
  84946. },
  84947. /**
  84948. * Specifies the horizontal size of the blur.
  84949. */
  84950. set: function (value) {
  84951. this._horizontalBlurPostprocess.kernel = value;
  84952. },
  84953. enumerable: true,
  84954. configurable: true
  84955. });
  84956. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  84957. /**
  84958. * Gets the vertical size of the blur.
  84959. */
  84960. get: function () {
  84961. return this._verticalBlurPostprocess.kernel;
  84962. },
  84963. /**
  84964. * Specifies the vertical size of the blur.
  84965. */
  84966. set: function (value) {
  84967. this._verticalBlurPostprocess.kernel = value;
  84968. },
  84969. enumerable: true,
  84970. configurable: true
  84971. });
  84972. /**
  84973. * Get the effect name of the layer.
  84974. * @return The effect name
  84975. */
  84976. HighlightLayer.prototype.getEffectName = function () {
  84977. return HighlightLayer.EffectName;
  84978. };
  84979. /**
  84980. * Create the merge effect. This is the shader use to blit the information back
  84981. * to the main canvas at the end of the scene rendering.
  84982. */
  84983. HighlightLayer.prototype._createMergeEffect = function () {
  84984. // Effect
  84985. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  84986. };
  84987. /**
  84988. * Creates the render target textures and post processes used in the highlight layer.
  84989. */
  84990. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  84991. var _this = this;
  84992. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  84993. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  84994. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84995. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84996. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  84997. width: blurTextureWidth,
  84998. height: blurTextureHeight
  84999. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85000. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85001. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85002. this._blurTexture.anisotropicFilteringLevel = 16;
  85003. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85004. this._blurTexture.renderParticles = false;
  85005. this._blurTexture.ignoreCameraViewport = true;
  85006. this._textures = [this._blurTexture];
  85007. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  85008. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85009. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  85010. effect.setTexture("textureSampler", _this._mainTexture);
  85011. });
  85012. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85013. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85014. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85015. });
  85016. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85017. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  85018. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85019. });
  85020. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85021. }
  85022. else {
  85023. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  85024. width: blurTextureWidth,
  85025. height: blurTextureHeight
  85026. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85027. this._horizontalBlurPostprocess.width = blurTextureWidth;
  85028. this._horizontalBlurPostprocess.height = blurTextureHeight;
  85029. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85030. effect.setTexture("textureSampler", _this._mainTexture);
  85031. });
  85032. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  85033. width: blurTextureWidth,
  85034. height: blurTextureHeight
  85035. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85036. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85037. }
  85038. this._mainTexture.onAfterUnbindObservable.add(function () {
  85039. _this.onBeforeBlurObservable.notifyObservers(_this);
  85040. var internalTexture = _this._blurTexture.getInternalTexture();
  85041. if (internalTexture) {
  85042. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  85043. }
  85044. _this.onAfterBlurObservable.notifyObservers(_this);
  85045. });
  85046. // Prevent autoClear.
  85047. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85048. };
  85049. /**
  85050. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85051. */
  85052. HighlightLayer.prototype.needStencil = function () {
  85053. return true;
  85054. };
  85055. /**
  85056. * Checks for the readiness of the element composing the layer.
  85057. * @param subMesh the mesh to check for
  85058. * @param useInstances specify wether or not to use instances to render the mesh
  85059. * @param emissiveTexture the associated emissive texture used to generate the glow
  85060. * @return true if ready otherwise, false
  85061. */
  85062. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  85063. var material = subMesh.getMaterial();
  85064. var mesh = subMesh.getRenderingMesh();
  85065. if (!material || !mesh || !this._meshes) {
  85066. return false;
  85067. }
  85068. var emissiveTexture = null;
  85069. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85070. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85071. emissiveTexture = material.emissiveTexture;
  85072. }
  85073. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85074. };
  85075. /**
  85076. * Implementation specific of rendering the generating effect on the main canvas.
  85077. * @param effect The effect used to render through
  85078. */
  85079. HighlightLayer.prototype._internalRender = function (effect) {
  85080. // Texture
  85081. effect.setTexture("textureSampler", this._blurTexture);
  85082. // Cache
  85083. var engine = this._engine;
  85084. var previousStencilBuffer = engine.getStencilBuffer();
  85085. var previousStencilFunction = engine.getStencilFunction();
  85086. var previousStencilMask = engine.getStencilMask();
  85087. var previousStencilOperationPass = engine.getStencilOperationPass();
  85088. var previousStencilOperationFail = engine.getStencilOperationFail();
  85089. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  85090. var previousStencilReference = engine.getStencilFunctionReference();
  85091. // Stencil operations
  85092. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  85093. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  85094. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  85095. // Draw order
  85096. engine.setStencilMask(0x00);
  85097. engine.setStencilBuffer(true);
  85098. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  85099. // 2 passes inner outer
  85100. if (this.outerGlow) {
  85101. effect.setFloat("offset", 0);
  85102. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  85103. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85104. }
  85105. if (this.innerGlow) {
  85106. effect.setFloat("offset", 1);
  85107. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  85108. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85109. }
  85110. // Restore Cache
  85111. engine.setStencilFunction(previousStencilFunction);
  85112. engine.setStencilMask(previousStencilMask);
  85113. engine.setStencilBuffer(previousStencilBuffer);
  85114. engine.setStencilOperationPass(previousStencilOperationPass);
  85115. engine.setStencilOperationFail(previousStencilOperationFail);
  85116. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  85117. engine.setStencilFunctionReference(previousStencilReference);
  85118. };
  85119. /**
  85120. * Returns true if the layer contains information to display, otherwise false.
  85121. */
  85122. HighlightLayer.prototype.shouldRender = function () {
  85123. if (_super.prototype.shouldRender.call(this)) {
  85124. return this._meshes ? true : false;
  85125. }
  85126. return false;
  85127. };
  85128. /**
  85129. * Returns true if the mesh should render, otherwise false.
  85130. * @param mesh The mesh to render
  85131. * @returns true if it should render otherwise false
  85132. */
  85133. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  85134. // Excluded Mesh
  85135. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  85136. return false;
  85137. }
  85138. ;
  85139. return true;
  85140. };
  85141. /**
  85142. * Sets the required values for both the emissive texture and and the main color.
  85143. */
  85144. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85145. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85146. if (highlightLayerMesh) {
  85147. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  85148. }
  85149. else {
  85150. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85151. }
  85152. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85153. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85154. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  85155. }
  85156. else {
  85157. this._emissiveTextureAndColor.texture = null;
  85158. }
  85159. };
  85160. /**
  85161. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  85162. * @param mesh The mesh to exclude from the highlight layer
  85163. */
  85164. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  85165. if (!this._excludedMeshes) {
  85166. return;
  85167. }
  85168. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85169. if (!meshExcluded) {
  85170. this._excludedMeshes[mesh.uniqueId] = {
  85171. mesh: mesh,
  85172. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  85173. mesh.getEngine().setStencilBuffer(false);
  85174. }),
  85175. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  85176. mesh.getEngine().setStencilBuffer(true);
  85177. }),
  85178. };
  85179. }
  85180. };
  85181. /**
  85182. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  85183. * @param mesh The mesh to highlight
  85184. */
  85185. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  85186. if (!this._excludedMeshes) {
  85187. return;
  85188. }
  85189. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85190. if (meshExcluded) {
  85191. if (meshExcluded.beforeRender) {
  85192. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  85193. }
  85194. if (meshExcluded.afterRender) {
  85195. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  85196. }
  85197. }
  85198. this._excludedMeshes[mesh.uniqueId] = null;
  85199. };
  85200. /**
  85201. * Determine if a given mesh will be highlighted by the current HighlightLayer
  85202. * @param mesh mesh to test
  85203. * @returns true if the mesh will be highlighted by the current HighlightLayer
  85204. */
  85205. HighlightLayer.prototype.hasMesh = function (mesh) {
  85206. if (!this._meshes) {
  85207. return false;
  85208. }
  85209. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  85210. };
  85211. /**
  85212. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  85213. * @param mesh The mesh to highlight
  85214. * @param color The color of the highlight
  85215. * @param glowEmissiveOnly Extract the glow from the emissive texture
  85216. */
  85217. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  85218. var _this = this;
  85219. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  85220. if (!this._meshes) {
  85221. return;
  85222. }
  85223. var meshHighlight = this._meshes[mesh.uniqueId];
  85224. if (meshHighlight) {
  85225. meshHighlight.color = color;
  85226. }
  85227. else {
  85228. this._meshes[mesh.uniqueId] = {
  85229. mesh: mesh,
  85230. color: color,
  85231. // Lambda required for capture due to Observable this context
  85232. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  85233. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  85234. _this._defaultStencilReference(mesh);
  85235. }
  85236. else {
  85237. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  85238. }
  85239. }),
  85240. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  85241. glowEmissiveOnly: glowEmissiveOnly
  85242. };
  85243. }
  85244. this._shouldRender = true;
  85245. };
  85246. /**
  85247. * Remove a mesh from the highlight layer in order to make it stop glowing.
  85248. * @param mesh The mesh to highlight
  85249. */
  85250. HighlightLayer.prototype.removeMesh = function (mesh) {
  85251. if (!this._meshes) {
  85252. return;
  85253. }
  85254. var meshHighlight = this._meshes[mesh.uniqueId];
  85255. if (meshHighlight) {
  85256. if (meshHighlight.observerHighlight) {
  85257. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85258. }
  85259. if (meshHighlight.observerDefault) {
  85260. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85261. }
  85262. delete this._meshes[mesh.uniqueId];
  85263. }
  85264. this._shouldRender = false;
  85265. for (var meshHighlightToCheck in this._meshes) {
  85266. if (this._meshes[meshHighlightToCheck]) {
  85267. this._shouldRender = true;
  85268. break;
  85269. }
  85270. }
  85271. };
  85272. /**
  85273. * Force the stencil to the normal expected value for none glowing parts
  85274. */
  85275. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  85276. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  85277. };
  85278. /**
  85279. * Free any resources and references associated to a mesh.
  85280. * Internal use
  85281. * @param mesh The mesh to free.
  85282. */
  85283. HighlightLayer.prototype._disposeMesh = function (mesh) {
  85284. this.removeMesh(mesh);
  85285. this.removeExcludedMesh(mesh);
  85286. };
  85287. /**
  85288. * Dispose the highlight layer and free resources.
  85289. */
  85290. HighlightLayer.prototype.dispose = function () {
  85291. if (this._meshes) {
  85292. // Clean mesh references
  85293. for (var id in this._meshes) {
  85294. var meshHighlight = this._meshes[id];
  85295. if (meshHighlight && meshHighlight.mesh) {
  85296. if (meshHighlight.observerHighlight) {
  85297. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  85298. }
  85299. if (meshHighlight.observerDefault) {
  85300. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  85301. }
  85302. }
  85303. }
  85304. this._meshes = null;
  85305. }
  85306. if (this._excludedMeshes) {
  85307. for (var id in this._excludedMeshes) {
  85308. var meshHighlight = this._excludedMeshes[id];
  85309. if (meshHighlight) {
  85310. if (meshHighlight.beforeRender) {
  85311. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  85312. }
  85313. if (meshHighlight.afterRender) {
  85314. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  85315. }
  85316. }
  85317. }
  85318. this._excludedMeshes = null;
  85319. }
  85320. _super.prototype.dispose.call(this);
  85321. };
  85322. /**
  85323. * Effect Name of the highlight layer.
  85324. */
  85325. HighlightLayer.EffectName = "HighlightLayer";
  85326. /**
  85327. * The neutral color used during the preparation of the glow effect.
  85328. * This is black by default as the blend operation is a blend operation.
  85329. */
  85330. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  85331. /**
  85332. * Stencil value used for glowing meshes.
  85333. */
  85334. HighlightLayer.GlowingMeshStencilReference = 0x02;
  85335. /**
  85336. * Stencil value used for the other meshes in the scene.
  85337. */
  85338. HighlightLayer.NormalMeshStencilReference = 0x01;
  85339. return HighlightLayer;
  85340. }(BABYLON.EffectLayer));
  85341. BABYLON.HighlightLayer = HighlightLayer;
  85342. })(BABYLON || (BABYLON = {}));
  85343. //# sourceMappingURL=babylon.highlightLayer.js.map
  85344. var BABYLON;
  85345. (function (BABYLON) {
  85346. /**
  85347. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  85348. *
  85349. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85350. * glowy meshes to your scene.
  85351. *
  85352. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  85353. */
  85354. var GlowLayer = /** @class */ (function (_super) {
  85355. __extends(GlowLayer, _super);
  85356. /**
  85357. * Instantiates a new glow Layer and references it to the scene.
  85358. * @param name The name of the layer
  85359. * @param scene The scene to use the layer in
  85360. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  85361. */
  85362. function GlowLayer(name, scene, options) {
  85363. var _this = _super.call(this, name, scene) || this;
  85364. _this.name = name;
  85365. _this._intensity = 1.0;
  85366. _this._includedOnlyMeshes = [];
  85367. _this._excludedMeshes = [];
  85368. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  85369. // Adapt options
  85370. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  85371. // Initialize the layer
  85372. _this._init({
  85373. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  85374. camera: _this._options.camera,
  85375. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85376. mainTextureRatio: _this._options.mainTextureRatio
  85377. });
  85378. return _this;
  85379. }
  85380. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  85381. /**
  85382. * Gets the kernel size of the blur.
  85383. */
  85384. get: function () {
  85385. return this._horizontalBlurPostprocess1.kernel;
  85386. },
  85387. /**
  85388. * Sets the kernel size of the blur.
  85389. */
  85390. set: function (value) {
  85391. this._horizontalBlurPostprocess1.kernel = value;
  85392. this._verticalBlurPostprocess1.kernel = value;
  85393. this._horizontalBlurPostprocess2.kernel = value;
  85394. this._verticalBlurPostprocess2.kernel = value;
  85395. },
  85396. enumerable: true,
  85397. configurable: true
  85398. });
  85399. Object.defineProperty(GlowLayer.prototype, "intensity", {
  85400. /**
  85401. * Gets the glow intensity.
  85402. */
  85403. get: function () {
  85404. return this._intensity;
  85405. },
  85406. /**
  85407. * Sets the glow intensity.
  85408. */
  85409. set: function (value) {
  85410. this._intensity = value;
  85411. },
  85412. enumerable: true,
  85413. configurable: true
  85414. });
  85415. /**
  85416. * Get the effect name of the layer.
  85417. * @return The effect name
  85418. */
  85419. GlowLayer.prototype.getEffectName = function () {
  85420. return GlowLayer.EffectName;
  85421. };
  85422. /**
  85423. * Create the merge effect. This is the shader use to blit the information back
  85424. * to the main canvas at the end of the scene rendering.
  85425. */
  85426. GlowLayer.prototype._createMergeEffect = function () {
  85427. // Effect
  85428. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  85429. };
  85430. /**
  85431. * Creates the render target textures and post processes used in the glow layer.
  85432. */
  85433. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  85434. var _this = this;
  85435. var blurTextureWidth = this._mainTextureDesiredSize.width;
  85436. var blurTextureHeight = this._mainTextureDesiredSize.height;
  85437. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85438. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85439. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  85440. width: blurTextureWidth,
  85441. height: blurTextureHeight
  85442. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85443. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85444. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85445. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85446. this._blurTexture1.renderParticles = false;
  85447. this._blurTexture1.ignoreCameraViewport = true;
  85448. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  85449. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  85450. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  85451. width: blurTextureWidth2,
  85452. height: blurTextureHeight2
  85453. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85454. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85455. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85456. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85457. this._blurTexture2.renderParticles = false;
  85458. this._blurTexture2.ignoreCameraViewport = true;
  85459. this._textures = [this._blurTexture1, this._blurTexture2];
  85460. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85461. width: blurTextureWidth,
  85462. height: blurTextureHeight
  85463. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85464. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  85465. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  85466. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  85467. effect.setTexture("textureSampler", _this._mainTexture);
  85468. });
  85469. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85470. width: blurTextureWidth,
  85471. height: blurTextureHeight
  85472. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85473. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  85474. width: blurTextureWidth2,
  85475. height: blurTextureHeight2
  85476. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85477. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  85478. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  85479. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  85480. effect.setTexture("textureSampler", _this._blurTexture1);
  85481. });
  85482. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  85483. width: blurTextureWidth2,
  85484. height: blurTextureHeight2
  85485. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85486. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85487. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  85488. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  85489. this._mainTexture.samples = this._options.mainTextureSamples;
  85490. this._mainTexture.onAfterUnbindObservable.add(function () {
  85491. var internalTexture = _this._blurTexture1.getInternalTexture();
  85492. if (internalTexture) {
  85493. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  85494. internalTexture = _this._blurTexture2.getInternalTexture();
  85495. if (internalTexture) {
  85496. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  85497. }
  85498. }
  85499. });
  85500. // Prevent autoClear.
  85501. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85502. };
  85503. /**
  85504. * Checks for the readiness of the element composing the layer.
  85505. * @param subMesh the mesh to check for
  85506. * @param useInstances specify wether or not to use instances to render the mesh
  85507. * @param emissiveTexture the associated emissive texture used to generate the glow
  85508. * @return true if ready otherwise, false
  85509. */
  85510. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  85511. var material = subMesh.getMaterial();
  85512. var mesh = subMesh.getRenderingMesh();
  85513. if (!material || !mesh) {
  85514. return false;
  85515. }
  85516. var emissiveTexture = material.emissiveTexture;
  85517. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85518. };
  85519. /**
  85520. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85521. */
  85522. GlowLayer.prototype.needStencil = function () {
  85523. return false;
  85524. };
  85525. /**
  85526. * Implementation specific of rendering the generating effect on the main canvas.
  85527. * @param effect The effect used to render through
  85528. */
  85529. GlowLayer.prototype._internalRender = function (effect) {
  85530. // Texture
  85531. effect.setTexture("textureSampler", this._blurTexture1);
  85532. effect.setTexture("textureSampler2", this._blurTexture2);
  85533. effect.setFloat("offset", this._intensity);
  85534. // Cache
  85535. var engine = this._engine;
  85536. var previousStencilBuffer = engine.getStencilBuffer();
  85537. // Draw order
  85538. engine.setStencilBuffer(false);
  85539. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85540. // Draw order
  85541. engine.setStencilBuffer(previousStencilBuffer);
  85542. };
  85543. /**
  85544. * Sets the required values for both the emissive texture and and the main color.
  85545. */
  85546. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85547. var textureLevel = 1.0;
  85548. if (this.customEmissiveTextureSelector) {
  85549. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  85550. }
  85551. else {
  85552. if (material) {
  85553. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85554. if (this._emissiveTextureAndColor.texture) {
  85555. textureLevel = this._emissiveTextureAndColor.texture.level;
  85556. }
  85557. }
  85558. else {
  85559. this._emissiveTextureAndColor.texture = null;
  85560. }
  85561. }
  85562. if (this.customEmissiveColorSelector) {
  85563. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  85564. }
  85565. else {
  85566. if (material.emissiveColor) {
  85567. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  85568. }
  85569. else {
  85570. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85571. }
  85572. }
  85573. };
  85574. /**
  85575. * Returns true if the mesh should render, otherwise false.
  85576. * @param mesh The mesh to render
  85577. * @returns true if it should render otherwise false
  85578. */
  85579. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  85580. return this.hasMesh(mesh);
  85581. };
  85582. /**
  85583. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  85584. * @param mesh The mesh to exclude from the glow layer
  85585. */
  85586. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  85587. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  85588. this._excludedMeshes.push(mesh.uniqueId);
  85589. }
  85590. };
  85591. /**
  85592. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  85593. * @param mesh The mesh to remove
  85594. */
  85595. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  85596. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  85597. if (index !== -1) {
  85598. this._excludedMeshes.splice(index, 1);
  85599. }
  85600. };
  85601. /**
  85602. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  85603. * @param mesh The mesh to include in the glow layer
  85604. */
  85605. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  85606. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  85607. this._includedOnlyMeshes.push(mesh.uniqueId);
  85608. }
  85609. };
  85610. /**
  85611. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  85612. * @param mesh The mesh to remove
  85613. */
  85614. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  85615. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  85616. if (index !== -1) {
  85617. this._includedOnlyMeshes.splice(index, 1);
  85618. }
  85619. };
  85620. /**
  85621. * Determine if a given mesh will be used in the glow layer
  85622. * @param mesh The mesh to test
  85623. * @returns true if the mesh will be highlighted by the current glow layer
  85624. */
  85625. GlowLayer.prototype.hasMesh = function (mesh) {
  85626. // Included Mesh
  85627. if (this._includedOnlyMeshes.length) {
  85628. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  85629. }
  85630. ;
  85631. // Excluded Mesh
  85632. if (this._excludedMeshes.length) {
  85633. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  85634. }
  85635. ;
  85636. return true;
  85637. };
  85638. /**
  85639. * Free any resources and references associated to a mesh.
  85640. * Internal use
  85641. * @param mesh The mesh to free.
  85642. */
  85643. GlowLayer.prototype._disposeMesh = function (mesh) {
  85644. this.removeIncludedOnlyMesh(mesh);
  85645. this.removeExcludedMesh(mesh);
  85646. };
  85647. /**
  85648. * Effect Name of the layer.
  85649. */
  85650. GlowLayer.EffectName = "GlowLayer";
  85651. /**
  85652. * The default blur kernel size used for the glow.
  85653. */
  85654. GlowLayer.DefaultBlurKernelSize = 32;
  85655. /**
  85656. * The default texture size ratio used for the glow.
  85657. */
  85658. GlowLayer.DefaultTextureRatio = 0.5;
  85659. return GlowLayer;
  85660. }(BABYLON.EffectLayer));
  85661. BABYLON.GlowLayer = GlowLayer;
  85662. })(BABYLON || (BABYLON = {}));
  85663. //# sourceMappingURL=babylon.glowLayer.js.map
  85664. var BABYLON;
  85665. (function (BABYLON) {
  85666. /**
  85667. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  85668. */
  85669. var AssetTaskState;
  85670. (function (AssetTaskState) {
  85671. /**
  85672. * Initialization
  85673. */
  85674. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  85675. /**
  85676. * Running
  85677. */
  85678. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  85679. /**
  85680. * Done
  85681. */
  85682. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  85683. /**
  85684. * Error
  85685. */
  85686. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  85687. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  85688. /**
  85689. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  85690. */
  85691. var AbstractAssetTask = /** @class */ (function () {
  85692. /**
  85693. * Creates a new {BABYLON.AssetsManager}
  85694. * @param name defines the name of the task
  85695. */
  85696. function AbstractAssetTask(
  85697. /**
  85698. * Task name
  85699. */ name) {
  85700. this.name = name;
  85701. this._isCompleted = false;
  85702. this._taskState = AssetTaskState.INIT;
  85703. }
  85704. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  85705. /**
  85706. * Get if the task is completed
  85707. */
  85708. get: function () {
  85709. return this._isCompleted;
  85710. },
  85711. enumerable: true,
  85712. configurable: true
  85713. });
  85714. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  85715. /**
  85716. * Gets the current state of the task
  85717. */
  85718. get: function () {
  85719. return this._taskState;
  85720. },
  85721. enumerable: true,
  85722. configurable: true
  85723. });
  85724. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  85725. /**
  85726. * Gets the current error object (if task is in error)
  85727. */
  85728. get: function () {
  85729. return this._errorObject;
  85730. },
  85731. enumerable: true,
  85732. configurable: true
  85733. });
  85734. /**
  85735. * Internal only
  85736. * @ignore
  85737. */
  85738. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  85739. if (this._errorObject) {
  85740. return;
  85741. }
  85742. this._errorObject = {
  85743. message: message,
  85744. exception: exception
  85745. };
  85746. };
  85747. /**
  85748. * Execute the current task
  85749. * @param scene defines the scene where you want your assets to be loaded
  85750. * @param onSuccess is a callback called when the task is successfully executed
  85751. * @param onError is a callback called if an error occurs
  85752. */
  85753. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85754. var _this = this;
  85755. this._taskState = AssetTaskState.RUNNING;
  85756. this.runTask(scene, function () {
  85757. _this.onDoneCallback(onSuccess, onError);
  85758. }, function (msg, exception) {
  85759. _this.onErrorCallback(onError, msg, exception);
  85760. });
  85761. };
  85762. /**
  85763. * Execute the current task
  85764. * @param scene defines the scene where you want your assets to be loaded
  85765. * @param onSuccess is a callback called when the task is successfully executed
  85766. * @param onError is a callback called if an error occurs
  85767. */
  85768. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85769. throw new Error("runTask is not implemented");
  85770. };
  85771. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  85772. this._taskState = AssetTaskState.ERROR;
  85773. this._errorObject = {
  85774. message: message,
  85775. exception: exception
  85776. };
  85777. if (this.onError) {
  85778. this.onError(this, message, exception);
  85779. }
  85780. onError();
  85781. };
  85782. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  85783. try {
  85784. this._taskState = AssetTaskState.DONE;
  85785. this._isCompleted = true;
  85786. if (this.onSuccess) {
  85787. this.onSuccess(this);
  85788. }
  85789. onSuccess();
  85790. }
  85791. catch (e) {
  85792. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  85793. }
  85794. };
  85795. return AbstractAssetTask;
  85796. }());
  85797. BABYLON.AbstractAssetTask = AbstractAssetTask;
  85798. /**
  85799. * Class used to share progress information about assets loading
  85800. */
  85801. var AssetsProgressEvent = /** @class */ (function () {
  85802. /**
  85803. * Creates a {BABYLON.AssetsProgressEvent}
  85804. * @param remainingCount defines the number of remaining tasks to process
  85805. * @param totalCount defines the total number of tasks
  85806. * @param task defines the task that was just processed
  85807. */
  85808. function AssetsProgressEvent(remainingCount, totalCount, task) {
  85809. this.remainingCount = remainingCount;
  85810. this.totalCount = totalCount;
  85811. this.task = task;
  85812. }
  85813. return AssetsProgressEvent;
  85814. }());
  85815. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  85816. /**
  85817. * Define a task used by {BABYLON.AssetsManager} to load meshes
  85818. */
  85819. var MeshAssetTask = /** @class */ (function (_super) {
  85820. __extends(MeshAssetTask, _super);
  85821. /**
  85822. * Creates a new {BABYLON.MeshAssetTask}
  85823. * @param name defines the name of the task
  85824. * @param meshesNames defines the list of mesh's names you want to load
  85825. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  85826. * @param sceneFilename defines the filename of the scene to load from
  85827. */
  85828. function MeshAssetTask(
  85829. /**
  85830. * Defines the name of the task
  85831. */
  85832. name,
  85833. /**
  85834. * Defines the list of mesh's names you want to load
  85835. */
  85836. meshesNames,
  85837. /**
  85838. * Defines the root url to use as a base to load your meshes and associated resources
  85839. */
  85840. rootUrl,
  85841. /**
  85842. * Defines the filename of the scene to load from
  85843. */
  85844. sceneFilename) {
  85845. var _this = _super.call(this, name) || this;
  85846. _this.name = name;
  85847. _this.meshesNames = meshesNames;
  85848. _this.rootUrl = rootUrl;
  85849. _this.sceneFilename = sceneFilename;
  85850. return _this;
  85851. }
  85852. /**
  85853. * Execute the current task
  85854. * @param scene defines the scene where you want your assets to be loaded
  85855. * @param onSuccess is a callback called when the task is successfully executed
  85856. * @param onError is a callback called if an error occurs
  85857. */
  85858. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85859. var _this = this;
  85860. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  85861. _this.loadedMeshes = meshes;
  85862. _this.loadedParticleSystems = particleSystems;
  85863. _this.loadedSkeletons = skeletons;
  85864. onSuccess();
  85865. }, null, function (scene, message, exception) {
  85866. onError(message, exception);
  85867. });
  85868. };
  85869. return MeshAssetTask;
  85870. }(AbstractAssetTask));
  85871. BABYLON.MeshAssetTask = MeshAssetTask;
  85872. /**
  85873. * Define a task used by {BABYLON.AssetsManager} to load text content
  85874. */
  85875. var TextFileAssetTask = /** @class */ (function (_super) {
  85876. __extends(TextFileAssetTask, _super);
  85877. /**
  85878. * Creates a new TextFileAssetTask object
  85879. * @param name defines the name of the task
  85880. * @param url defines the location of the file to load
  85881. */
  85882. function TextFileAssetTask(
  85883. /**
  85884. * Defines the name of the task
  85885. */
  85886. name,
  85887. /**
  85888. * Defines the location of the file to load
  85889. */
  85890. url) {
  85891. var _this = _super.call(this, name) || this;
  85892. _this.name = name;
  85893. _this.url = url;
  85894. return _this;
  85895. }
  85896. /**
  85897. * Execute the current task
  85898. * @param scene defines the scene where you want your assets to be loaded
  85899. * @param onSuccess is a callback called when the task is successfully executed
  85900. * @param onError is a callback called if an error occurs
  85901. */
  85902. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85903. var _this = this;
  85904. scene._loadFile(this.url, function (data) {
  85905. _this.text = data;
  85906. onSuccess();
  85907. }, undefined, false, false, function (request, exception) {
  85908. if (request) {
  85909. onError(request.status + " " + request.statusText, exception);
  85910. }
  85911. });
  85912. };
  85913. return TextFileAssetTask;
  85914. }(AbstractAssetTask));
  85915. BABYLON.TextFileAssetTask = TextFileAssetTask;
  85916. /**
  85917. * Define a task used by {BABYLON.AssetsManager} to load binary data
  85918. */
  85919. var BinaryFileAssetTask = /** @class */ (function (_super) {
  85920. __extends(BinaryFileAssetTask, _super);
  85921. /**
  85922. * Creates a new BinaryFileAssetTask object
  85923. * @param name defines the name of the new task
  85924. * @param url defines the location of the file to load
  85925. */
  85926. function BinaryFileAssetTask(
  85927. /**
  85928. * Defines the name of the task
  85929. */
  85930. name,
  85931. /**
  85932. * Defines the location of the file to load
  85933. */
  85934. url) {
  85935. var _this = _super.call(this, name) || this;
  85936. _this.name = name;
  85937. _this.url = url;
  85938. return _this;
  85939. }
  85940. /**
  85941. * Execute the current task
  85942. * @param scene defines the scene where you want your assets to be loaded
  85943. * @param onSuccess is a callback called when the task is successfully executed
  85944. * @param onError is a callback called if an error occurs
  85945. */
  85946. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85947. var _this = this;
  85948. scene._loadFile(this.url, function (data) {
  85949. _this.data = data;
  85950. onSuccess();
  85951. }, undefined, true, true, function (request, exception) {
  85952. if (request) {
  85953. onError(request.status + " " + request.statusText, exception);
  85954. }
  85955. });
  85956. };
  85957. return BinaryFileAssetTask;
  85958. }(AbstractAssetTask));
  85959. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  85960. /**
  85961. * Define a task used by {BABYLON.AssetsManager} to load images
  85962. */
  85963. var ImageAssetTask = /** @class */ (function (_super) {
  85964. __extends(ImageAssetTask, _super);
  85965. /**
  85966. * Creates a new ImageAssetTask
  85967. * @param name defines the name of the task
  85968. * @param url defines the location of the image to load
  85969. */
  85970. function ImageAssetTask(
  85971. /**
  85972. * Defines the name of the task
  85973. */
  85974. name,
  85975. /**
  85976. * Defines the location of the image to load
  85977. */
  85978. url) {
  85979. var _this = _super.call(this, name) || this;
  85980. _this.name = name;
  85981. _this.url = url;
  85982. return _this;
  85983. }
  85984. /**
  85985. * Execute the current task
  85986. * @param scene defines the scene where you want your assets to be loaded
  85987. * @param onSuccess is a callback called when the task is successfully executed
  85988. * @param onError is a callback called if an error occurs
  85989. */
  85990. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85991. var _this = this;
  85992. var img = new Image();
  85993. BABYLON.Tools.SetCorsBehavior(this.url, img);
  85994. img.onload = function () {
  85995. _this.image = img;
  85996. onSuccess();
  85997. };
  85998. img.onerror = function (err) {
  85999. onError("Error loading image", err);
  86000. };
  86001. img.src = this.url;
  86002. };
  86003. return ImageAssetTask;
  86004. }(AbstractAssetTask));
  86005. BABYLON.ImageAssetTask = ImageAssetTask;
  86006. /**
  86007. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  86008. */
  86009. var TextureAssetTask = /** @class */ (function (_super) {
  86010. __extends(TextureAssetTask, _super);
  86011. /**
  86012. * Creates a new TextureAssetTask object
  86013. * @param name defines the name of the task
  86014. * @param url defines the location of the file to load
  86015. * @param noMipmap defines if mipmap should not be generated (default is false)
  86016. * @param invertY defines if texture must be inverted on Y axis (default is false)
  86017. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86018. */
  86019. function TextureAssetTask(
  86020. /**
  86021. * Defines the name of the task
  86022. */
  86023. name,
  86024. /**
  86025. * Defines the location of the file to load
  86026. */
  86027. url,
  86028. /**
  86029. * Defines if mipmap should not be generated (default is false)
  86030. */
  86031. noMipmap,
  86032. /**
  86033. * Defines if texture must be inverted on Y axis (default is false)
  86034. */
  86035. invertY,
  86036. /**
  86037. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86038. */
  86039. samplingMode) {
  86040. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86041. var _this = _super.call(this, name) || this;
  86042. _this.name = name;
  86043. _this.url = url;
  86044. _this.noMipmap = noMipmap;
  86045. _this.invertY = invertY;
  86046. _this.samplingMode = samplingMode;
  86047. return _this;
  86048. }
  86049. /**
  86050. * Execute the current task
  86051. * @param scene defines the scene where you want your assets to be loaded
  86052. * @param onSuccess is a callback called when the task is successfully executed
  86053. * @param onError is a callback called if an error occurs
  86054. */
  86055. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86056. var onload = function () {
  86057. onSuccess();
  86058. };
  86059. var onerror = function (message, exception) {
  86060. onError(message, exception);
  86061. };
  86062. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  86063. };
  86064. return TextureAssetTask;
  86065. }(AbstractAssetTask));
  86066. BABYLON.TextureAssetTask = TextureAssetTask;
  86067. /**
  86068. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  86069. */
  86070. var CubeTextureAssetTask = /** @class */ (function (_super) {
  86071. __extends(CubeTextureAssetTask, _super);
  86072. /**
  86073. * Creates a new CubeTextureAssetTask
  86074. * @param name defines the name of the task
  86075. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86076. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86077. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86078. * @param files defines the explicit list of files (undefined by default)
  86079. */
  86080. function CubeTextureAssetTask(
  86081. /**
  86082. * Defines the name of the task
  86083. */
  86084. name,
  86085. /**
  86086. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86087. */
  86088. url,
  86089. /**
  86090. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86091. */
  86092. extensions,
  86093. /**
  86094. * Defines if mipmaps should not be generated (default is false)
  86095. */
  86096. noMipmap,
  86097. /**
  86098. * Defines the explicit list of files (undefined by default)
  86099. */
  86100. files) {
  86101. var _this = _super.call(this, name) || this;
  86102. _this.name = name;
  86103. _this.url = url;
  86104. _this.extensions = extensions;
  86105. _this.noMipmap = noMipmap;
  86106. _this.files = files;
  86107. return _this;
  86108. }
  86109. /**
  86110. * Execute the current task
  86111. * @param scene defines the scene where you want your assets to be loaded
  86112. * @param onSuccess is a callback called when the task is successfully executed
  86113. * @param onError is a callback called if an error occurs
  86114. */
  86115. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86116. var onload = function () {
  86117. onSuccess();
  86118. };
  86119. var onerror = function (message, exception) {
  86120. onError(message, exception);
  86121. };
  86122. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  86123. };
  86124. return CubeTextureAssetTask;
  86125. }(AbstractAssetTask));
  86126. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  86127. /**
  86128. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  86129. */
  86130. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  86131. __extends(HDRCubeTextureAssetTask, _super);
  86132. /**
  86133. * Creates a new HDRCubeTextureAssetTask object
  86134. * @param name defines the name of the task
  86135. * @param url defines the location of the file to load
  86136. * @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.
  86137. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86138. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86139. * @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)
  86140. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86141. */
  86142. function HDRCubeTextureAssetTask(
  86143. /**
  86144. * Defines the name of the task
  86145. */
  86146. name,
  86147. /**
  86148. * Defines the location of the file to load
  86149. */
  86150. url,
  86151. /**
  86152. * 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.
  86153. */
  86154. size,
  86155. /**
  86156. * Defines if mipmaps should not be generated (default is false)
  86157. */
  86158. noMipmap,
  86159. /**
  86160. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86161. */
  86162. generateHarmonics,
  86163. /**
  86164. * 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)
  86165. */
  86166. useInGammaSpace,
  86167. /**
  86168. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86169. */
  86170. usePMREMGenerator) {
  86171. if (noMipmap === void 0) { noMipmap = false; }
  86172. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86173. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86174. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86175. var _this = _super.call(this, name) || this;
  86176. _this.name = name;
  86177. _this.url = url;
  86178. _this.size = size;
  86179. _this.noMipmap = noMipmap;
  86180. _this.generateHarmonics = generateHarmonics;
  86181. _this.useInGammaSpace = useInGammaSpace;
  86182. _this.usePMREMGenerator = usePMREMGenerator;
  86183. return _this;
  86184. }
  86185. /**
  86186. * Execute the current task
  86187. * @param scene defines the scene where you want your assets to be loaded
  86188. * @param onSuccess is a callback called when the task is successfully executed
  86189. * @param onError is a callback called if an error occurs
  86190. */
  86191. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86192. var onload = function () {
  86193. onSuccess();
  86194. };
  86195. var onerror = function (message, exception) {
  86196. onError(message, exception);
  86197. };
  86198. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  86199. };
  86200. return HDRCubeTextureAssetTask;
  86201. }(AbstractAssetTask));
  86202. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  86203. /**
  86204. * This class can be used to easily import assets into a scene
  86205. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  86206. */
  86207. var AssetsManager = /** @class */ (function () {
  86208. /**
  86209. * Creates a new AssetsManager
  86210. * @param scene defines the scene to work on
  86211. */
  86212. function AssetsManager(scene) {
  86213. this._isLoading = false;
  86214. this._tasks = new Array();
  86215. this._waitingTasksCount = 0;
  86216. this._totalTasksCount = 0;
  86217. /**
  86218. * Observable called when all tasks are processed
  86219. */
  86220. this.onTaskSuccessObservable = new BABYLON.Observable();
  86221. /**
  86222. * Observable called when a task had an error
  86223. */
  86224. this.onTaskErrorObservable = new BABYLON.Observable();
  86225. /**
  86226. * Observable called when a task is successful
  86227. */
  86228. this.onTasksDoneObservable = new BABYLON.Observable();
  86229. /**
  86230. * Observable called when a task is done (whatever the result is)
  86231. */
  86232. this.onProgressObservable = new BABYLON.Observable();
  86233. /**
  86234. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  86235. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  86236. */
  86237. this.useDefaultLoadingScreen = true;
  86238. this._scene = scene;
  86239. }
  86240. /**
  86241. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  86242. * @param taskName defines the name of the new task
  86243. * @param meshesNames defines the name of meshes to load
  86244. * @param rootUrl defines the root url to use to locate files
  86245. * @param sceneFilename defines the filename of the scene file
  86246. * @returns a new {BABYLON.MeshAssetTask} object
  86247. */
  86248. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  86249. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  86250. this._tasks.push(task);
  86251. return task;
  86252. };
  86253. /**
  86254. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  86255. * @param taskName defines the name of the new task
  86256. * @param url defines the url of the file to load
  86257. * @returns a new {BABYLON.TextFileAssetTask} object
  86258. */
  86259. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  86260. var task = new TextFileAssetTask(taskName, url);
  86261. this._tasks.push(task);
  86262. return task;
  86263. };
  86264. /**
  86265. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  86266. * @param taskName defines the name of the new task
  86267. * @param url defines the url of the file to load
  86268. * @returns a new {BABYLON.BinaryFileAssetTask} object
  86269. */
  86270. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  86271. var task = new BinaryFileAssetTask(taskName, url);
  86272. this._tasks.push(task);
  86273. return task;
  86274. };
  86275. /**
  86276. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  86277. * @param taskName defines the name of the new task
  86278. * @param url defines the url of the file to load
  86279. * @returns a new {BABYLON.ImageAssetTask} object
  86280. */
  86281. AssetsManager.prototype.addImageTask = function (taskName, url) {
  86282. var task = new ImageAssetTask(taskName, url);
  86283. this._tasks.push(task);
  86284. return task;
  86285. };
  86286. /**
  86287. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  86288. * @param taskName defines the name of the new task
  86289. * @param url defines the url of the file to load
  86290. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86291. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  86292. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  86293. * @returns a new {BABYLON.TextureAssetTask} object
  86294. */
  86295. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  86296. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86297. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  86298. this._tasks.push(task);
  86299. return task;
  86300. };
  86301. /**
  86302. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  86303. * @param taskName defines the name of the new task
  86304. * @param url defines the url of the file to load
  86305. * @param extensions defines the extension to use to load the cube map (can be null)
  86306. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86307. * @param files defines the list of files to load (can be null)
  86308. * @returns a new {BABYLON.CubeTextureAssetTask} object
  86309. */
  86310. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  86311. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  86312. this._tasks.push(task);
  86313. return task;
  86314. };
  86315. /**
  86316. *
  86317. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  86318. * @param taskName defines the name of the new task
  86319. * @param url defines the url of the file to load
  86320. * @param size defines the size you want for the cubemap (can be null)
  86321. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  86322. * @param generateHarmonics defines if you want to automatically generate (true by default)
  86323. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  86324. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  86325. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  86326. */
  86327. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  86328. if (noMipmap === void 0) { noMipmap = false; }
  86329. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86330. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86331. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86332. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  86333. this._tasks.push(task);
  86334. return task;
  86335. };
  86336. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  86337. var _this = this;
  86338. this._waitingTasksCount--;
  86339. try {
  86340. if (task.taskState === AssetTaskState.DONE) {
  86341. // Let's remove successfull tasks
  86342. BABYLON.Tools.SetImmediate(function () {
  86343. var index = _this._tasks.indexOf(task);
  86344. if (index > -1) {
  86345. _this._tasks.splice(index, 1);
  86346. }
  86347. });
  86348. }
  86349. if (this.onProgress) {
  86350. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  86351. }
  86352. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  86353. }
  86354. catch (e) {
  86355. BABYLON.Tools.Error("Error running progress callbacks.");
  86356. console.log(e);
  86357. }
  86358. if (this._waitingTasksCount === 0) {
  86359. try {
  86360. if (this.onFinish) {
  86361. this.onFinish(this._tasks);
  86362. }
  86363. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86364. }
  86365. catch (e) {
  86366. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  86367. console.log(e);
  86368. }
  86369. this._isLoading = false;
  86370. this._scene.getEngine().hideLoadingUI();
  86371. }
  86372. };
  86373. AssetsManager.prototype._runTask = function (task) {
  86374. var _this = this;
  86375. var done = function () {
  86376. try {
  86377. if (_this.onTaskSuccess) {
  86378. _this.onTaskSuccess(task);
  86379. }
  86380. _this.onTaskSuccessObservable.notifyObservers(task);
  86381. _this._decreaseWaitingTasksCount(task);
  86382. }
  86383. catch (e) {
  86384. error("Error executing task success callbacks", e);
  86385. }
  86386. };
  86387. var error = function (message, exception) {
  86388. task._setErrorObject(message, exception);
  86389. if (_this.onTaskError) {
  86390. _this.onTaskError(task);
  86391. }
  86392. _this.onTaskErrorObservable.notifyObservers(task);
  86393. _this._decreaseWaitingTasksCount(task);
  86394. };
  86395. task.run(this._scene, done, error);
  86396. };
  86397. /**
  86398. * Reset the {BABYLON.AssetsManager} and remove all tasks
  86399. * @return the current instance of the {BABYLON.AssetsManager}
  86400. */
  86401. AssetsManager.prototype.reset = function () {
  86402. this._isLoading = false;
  86403. this._tasks = new Array();
  86404. return this;
  86405. };
  86406. /**
  86407. * Start the loading process
  86408. * @return the current instance of the {BABYLON.AssetsManager}
  86409. */
  86410. AssetsManager.prototype.load = function () {
  86411. if (this._isLoading) {
  86412. return this;
  86413. }
  86414. this._isLoading = true;
  86415. this._waitingTasksCount = this._tasks.length;
  86416. this._totalTasksCount = this._tasks.length;
  86417. if (this._waitingTasksCount === 0) {
  86418. this._isLoading = false;
  86419. if (this.onFinish) {
  86420. this.onFinish(this._tasks);
  86421. }
  86422. this.onTasksDoneObservable.notifyObservers(this._tasks);
  86423. return this;
  86424. }
  86425. if (this.useDefaultLoadingScreen) {
  86426. this._scene.getEngine().displayLoadingUI();
  86427. }
  86428. for (var index = 0; index < this._tasks.length; index++) {
  86429. var task = this._tasks[index];
  86430. this._runTask(task);
  86431. }
  86432. return this;
  86433. };
  86434. return AssetsManager;
  86435. }());
  86436. BABYLON.AssetsManager = AssetsManager;
  86437. })(BABYLON || (BABYLON = {}));
  86438. //# sourceMappingURL=babylon.assetsManager.js.map
  86439. var BABYLON;
  86440. (function (BABYLON) {
  86441. var serializedGeometries = [];
  86442. var serializeGeometry = function (geometry, serializationGeometries) {
  86443. if (serializedGeometries[geometry.id]) {
  86444. return;
  86445. }
  86446. if (geometry.doNotSerialize) {
  86447. return;
  86448. }
  86449. if (geometry instanceof BABYLON.BoxGeometry) {
  86450. serializationGeometries.boxes.push(geometry.serialize());
  86451. }
  86452. else if (geometry instanceof BABYLON.SphereGeometry) {
  86453. serializationGeometries.spheres.push(geometry.serialize());
  86454. }
  86455. else if (geometry instanceof BABYLON.CylinderGeometry) {
  86456. serializationGeometries.cylinders.push(geometry.serialize());
  86457. }
  86458. else if (geometry instanceof BABYLON.TorusGeometry) {
  86459. serializationGeometries.toruses.push(geometry.serialize());
  86460. }
  86461. else if (geometry instanceof BABYLON.GroundGeometry) {
  86462. serializationGeometries.grounds.push(geometry.serialize());
  86463. }
  86464. else if (geometry instanceof BABYLON.Plane) {
  86465. serializationGeometries.planes.push(geometry.serialize());
  86466. }
  86467. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  86468. serializationGeometries.torusKnots.push(geometry.serialize());
  86469. }
  86470. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  86471. throw new Error("Unknown primitive type");
  86472. }
  86473. else {
  86474. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  86475. }
  86476. serializedGeometries[geometry.id] = true;
  86477. };
  86478. var serializeMesh = function (mesh, serializationScene) {
  86479. var serializationObject = {};
  86480. // Geometry
  86481. var geometry = mesh._geometry;
  86482. if (geometry) {
  86483. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  86484. // 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
  86485. serializeGeometry(geometry, serializationScene.geometries);
  86486. }
  86487. }
  86488. // Custom
  86489. if (mesh.serialize) {
  86490. mesh.serialize(serializationObject);
  86491. }
  86492. return serializationObject;
  86493. };
  86494. var finalizeSingleMesh = function (mesh, serializationObject) {
  86495. //only works if the mesh is already loaded
  86496. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86497. //serialize material
  86498. if (mesh.material) {
  86499. if (mesh.material instanceof BABYLON.StandardMaterial) {
  86500. serializationObject.materials = serializationObject.materials || [];
  86501. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86502. serializationObject.materials.push(mesh.material.serialize());
  86503. }
  86504. }
  86505. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  86506. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  86507. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  86508. serializationObject.multiMaterials.push(mesh.material.serialize());
  86509. }
  86510. }
  86511. }
  86512. //serialize geometry
  86513. var geometry = mesh._geometry;
  86514. if (geometry) {
  86515. if (!serializationObject.geometries) {
  86516. serializationObject.geometries = {};
  86517. serializationObject.geometries.boxes = [];
  86518. serializationObject.geometries.spheres = [];
  86519. serializationObject.geometries.cylinders = [];
  86520. serializationObject.geometries.toruses = [];
  86521. serializationObject.geometries.grounds = [];
  86522. serializationObject.geometries.planes = [];
  86523. serializationObject.geometries.torusKnots = [];
  86524. serializationObject.geometries.vertexData = [];
  86525. }
  86526. serializeGeometry(geometry, serializationObject.geometries);
  86527. }
  86528. // Skeletons
  86529. if (mesh.skeleton) {
  86530. serializationObject.skeletons = serializationObject.skeletons || [];
  86531. serializationObject.skeletons.push(mesh.skeleton.serialize());
  86532. }
  86533. //serialize the actual mesh
  86534. serializationObject.meshes = serializationObject.meshes || [];
  86535. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86536. }
  86537. };
  86538. var SceneSerializer = /** @class */ (function () {
  86539. function SceneSerializer() {
  86540. }
  86541. SceneSerializer.ClearCache = function () {
  86542. serializedGeometries = [];
  86543. };
  86544. SceneSerializer.Serialize = function (scene) {
  86545. var serializationObject = {};
  86546. SceneSerializer.ClearCache();
  86547. // Scene
  86548. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  86549. serializationObject.autoClear = scene.autoClear;
  86550. serializationObject.clearColor = scene.clearColor.asArray();
  86551. serializationObject.ambientColor = scene.ambientColor.asArray();
  86552. serializationObject.gravity = scene.gravity.asArray();
  86553. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  86554. serializationObject.workerCollisions = scene.workerCollisions;
  86555. // Fog
  86556. if (scene.fogMode && scene.fogMode !== 0) {
  86557. serializationObject.fogMode = scene.fogMode;
  86558. serializationObject.fogColor = scene.fogColor.asArray();
  86559. serializationObject.fogStart = scene.fogStart;
  86560. serializationObject.fogEnd = scene.fogEnd;
  86561. serializationObject.fogDensity = scene.fogDensity;
  86562. }
  86563. //Physics
  86564. if (scene.isPhysicsEnabled()) {
  86565. var physicEngine = scene.getPhysicsEngine();
  86566. if (physicEngine) {
  86567. serializationObject.physicsEnabled = true;
  86568. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  86569. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  86570. }
  86571. }
  86572. // Metadata
  86573. if (scene.metadata) {
  86574. serializationObject.metadata = scene.metadata;
  86575. }
  86576. // Morph targets
  86577. serializationObject.morphTargetManagers = [];
  86578. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  86579. var abstractMesh = _a[_i];
  86580. var manager = abstractMesh.morphTargetManager;
  86581. if (manager) {
  86582. serializationObject.morphTargetManagers.push(manager.serialize());
  86583. }
  86584. }
  86585. // Lights
  86586. serializationObject.lights = [];
  86587. var index;
  86588. var light;
  86589. for (index = 0; index < scene.lights.length; index++) {
  86590. light = scene.lights[index];
  86591. if (!light.doNotSerialize) {
  86592. serializationObject.lights.push(light.serialize());
  86593. }
  86594. }
  86595. // Cameras
  86596. serializationObject.cameras = [];
  86597. for (index = 0; index < scene.cameras.length; index++) {
  86598. var camera = scene.cameras[index];
  86599. if (!camera.doNotSerialize) {
  86600. serializationObject.cameras.push(camera.serialize());
  86601. }
  86602. }
  86603. if (scene.activeCamera) {
  86604. serializationObject.activeCameraID = scene.activeCamera.id;
  86605. }
  86606. // Animations
  86607. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  86608. // Materials
  86609. serializationObject.materials = [];
  86610. serializationObject.multiMaterials = [];
  86611. var material;
  86612. for (index = 0; index < scene.materials.length; index++) {
  86613. material = scene.materials[index];
  86614. if (!material.doNotSerialize) {
  86615. serializationObject.materials.push(material.serialize());
  86616. }
  86617. }
  86618. // MultiMaterials
  86619. serializationObject.multiMaterials = [];
  86620. for (index = 0; index < scene.multiMaterials.length; index++) {
  86621. var multiMaterial = scene.multiMaterials[index];
  86622. serializationObject.multiMaterials.push(multiMaterial.serialize());
  86623. }
  86624. // Environment texture
  86625. if (scene.environmentTexture) {
  86626. serializationObject.environmentTexture = scene.environmentTexture.name;
  86627. }
  86628. // Skeletons
  86629. serializationObject.skeletons = [];
  86630. for (index = 0; index < scene.skeletons.length; index++) {
  86631. var skeleton = scene.skeletons[index];
  86632. if (!skeleton.doNotSerialize) {
  86633. serializationObject.skeletons.push(skeleton.serialize());
  86634. }
  86635. }
  86636. // Transform nodes
  86637. serializationObject.transformNodes = [];
  86638. for (index = 0; index < scene.transformNodes.length; index++) {
  86639. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  86640. }
  86641. // Geometries
  86642. serializationObject.geometries = {};
  86643. serializationObject.geometries.boxes = [];
  86644. serializationObject.geometries.spheres = [];
  86645. serializationObject.geometries.cylinders = [];
  86646. serializationObject.geometries.toruses = [];
  86647. serializationObject.geometries.grounds = [];
  86648. serializationObject.geometries.planes = [];
  86649. serializationObject.geometries.torusKnots = [];
  86650. serializationObject.geometries.vertexData = [];
  86651. serializedGeometries = [];
  86652. var geometries = scene.getGeometries();
  86653. for (index = 0; index < geometries.length; index++) {
  86654. var geometry = geometries[index];
  86655. if (geometry.isReady()) {
  86656. serializeGeometry(geometry, serializationObject.geometries);
  86657. }
  86658. }
  86659. // Meshes
  86660. serializationObject.meshes = [];
  86661. for (index = 0; index < scene.meshes.length; index++) {
  86662. var abstractMesh = scene.meshes[index];
  86663. if (abstractMesh instanceof BABYLON.Mesh) {
  86664. var mesh = abstractMesh;
  86665. if (!mesh.doNotSerialize) {
  86666. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86667. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86668. }
  86669. }
  86670. }
  86671. }
  86672. // Particles Systems
  86673. serializationObject.particleSystems = [];
  86674. for (index = 0; index < scene.particleSystems.length; index++) {
  86675. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  86676. }
  86677. // Lens flares
  86678. serializationObject.lensFlareSystems = [];
  86679. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  86680. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  86681. }
  86682. // Shadows
  86683. serializationObject.shadowGenerators = [];
  86684. for (index = 0; index < scene.lights.length; index++) {
  86685. light = scene.lights[index];
  86686. var shadowGenerator = light.getShadowGenerator();
  86687. if (shadowGenerator) {
  86688. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  86689. }
  86690. }
  86691. // Action Manager
  86692. if (scene.actionManager) {
  86693. serializationObject.actions = scene.actionManager.serialize("scene");
  86694. }
  86695. // Audio
  86696. serializationObject.sounds = [];
  86697. for (index = 0; index < scene.soundTracks.length; index++) {
  86698. var soundtrack = scene.soundTracks[index];
  86699. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  86700. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  86701. }
  86702. }
  86703. return serializationObject;
  86704. };
  86705. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  86706. if (withParents === void 0) { withParents = false; }
  86707. if (withChildren === void 0) { withChildren = false; }
  86708. var serializationObject = {};
  86709. SceneSerializer.ClearCache();
  86710. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  86711. if (withParents || withChildren) {
  86712. //deliberate for loop! not for each, appended should be processed as well.
  86713. for (var i = 0; i < toSerialize.length; ++i) {
  86714. if (withChildren) {
  86715. toSerialize[i].getDescendants().forEach(function (node) {
  86716. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  86717. toSerialize.push(node);
  86718. }
  86719. });
  86720. }
  86721. //make sure the array doesn't contain the object already
  86722. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  86723. toSerialize.push(toSerialize[i].parent);
  86724. }
  86725. }
  86726. }
  86727. toSerialize.forEach(function (mesh) {
  86728. finalizeSingleMesh(mesh, serializationObject);
  86729. });
  86730. return serializationObject;
  86731. };
  86732. return SceneSerializer;
  86733. }());
  86734. BABYLON.SceneSerializer = SceneSerializer;
  86735. })(BABYLON || (BABYLON = {}));
  86736. //# sourceMappingURL=babylon.sceneSerializer.js.map
  86737. var BABYLON;
  86738. (function (BABYLON) {
  86739. var ReflectionProbe = /** @class */ (function () {
  86740. function ReflectionProbe(name, size, scene, generateMipMaps) {
  86741. if (generateMipMaps === void 0) { generateMipMaps = true; }
  86742. var _this = this;
  86743. this.name = name;
  86744. this._viewMatrix = BABYLON.Matrix.Identity();
  86745. this._target = BABYLON.Vector3.Zero();
  86746. this._add = BABYLON.Vector3.Zero();
  86747. this._invertYAxis = false;
  86748. this.position = BABYLON.Vector3.Zero();
  86749. this._scene = scene;
  86750. this._scene.reflectionProbes.push(this);
  86751. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  86752. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  86753. switch (faceIndex) {
  86754. case 0:
  86755. _this._add.copyFromFloats(1, 0, 0);
  86756. break;
  86757. case 1:
  86758. _this._add.copyFromFloats(-1, 0, 0);
  86759. break;
  86760. case 2:
  86761. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  86762. break;
  86763. case 3:
  86764. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  86765. break;
  86766. case 4:
  86767. _this._add.copyFromFloats(0, 0, 1);
  86768. break;
  86769. case 5:
  86770. _this._add.copyFromFloats(0, 0, -1);
  86771. break;
  86772. }
  86773. if (_this._attachedMesh) {
  86774. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  86775. }
  86776. _this.position.addToRef(_this._add, _this._target);
  86777. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  86778. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  86779. scene._forcedViewPosition = _this.position;
  86780. });
  86781. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  86782. scene._forcedViewPosition = null;
  86783. scene.updateTransformMatrix(true);
  86784. });
  86785. if (scene.activeCamera) {
  86786. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86787. }
  86788. }
  86789. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  86790. get: function () {
  86791. return this._renderTargetTexture.samples;
  86792. },
  86793. set: function (value) {
  86794. this._renderTargetTexture.samples = value;
  86795. },
  86796. enumerable: true,
  86797. configurable: true
  86798. });
  86799. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  86800. get: function () {
  86801. return this._renderTargetTexture.refreshRate;
  86802. },
  86803. set: function (value) {
  86804. this._renderTargetTexture.refreshRate = value;
  86805. },
  86806. enumerable: true,
  86807. configurable: true
  86808. });
  86809. ReflectionProbe.prototype.getScene = function () {
  86810. return this._scene;
  86811. };
  86812. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  86813. get: function () {
  86814. return this._renderTargetTexture;
  86815. },
  86816. enumerable: true,
  86817. configurable: true
  86818. });
  86819. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  86820. get: function () {
  86821. return this._renderTargetTexture.renderList;
  86822. },
  86823. enumerable: true,
  86824. configurable: true
  86825. });
  86826. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  86827. this._attachedMesh = mesh;
  86828. };
  86829. /**
  86830. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  86831. *
  86832. * @param renderingGroupId The rendering group id corresponding to its index
  86833. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  86834. */
  86835. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  86836. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  86837. };
  86838. ReflectionProbe.prototype.dispose = function () {
  86839. var index = this._scene.reflectionProbes.indexOf(this);
  86840. if (index !== -1) {
  86841. // Remove from the scene if found
  86842. this._scene.reflectionProbes.splice(index, 1);
  86843. }
  86844. if (this._renderTargetTexture) {
  86845. this._renderTargetTexture.dispose();
  86846. this._renderTargetTexture = null;
  86847. }
  86848. };
  86849. return ReflectionProbe;
  86850. }());
  86851. BABYLON.ReflectionProbe = ReflectionProbe;
  86852. })(BABYLON || (BABYLON = {}));
  86853. //# sourceMappingURL=babylon.reflectionProbe.js.map
  86854. var BABYLON;
  86855. (function (BABYLON) {
  86856. var Layer = /** @class */ (function () {
  86857. function Layer(name, imgUrl, scene, isBackground, color) {
  86858. this.name = name;
  86859. this.scale = new BABYLON.Vector2(1, 1);
  86860. this.offset = new BABYLON.Vector2(0, 0);
  86861. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  86862. this.layerMask = 0x0FFFFFFF;
  86863. this._vertexBuffers = {};
  86864. // Events
  86865. /**
  86866. * An event triggered when the layer is disposed.
  86867. * @type {BABYLON.Observable}
  86868. */
  86869. this.onDisposeObservable = new BABYLON.Observable();
  86870. /**
  86871. * An event triggered before rendering the scene
  86872. * @type {BABYLON.Observable}
  86873. */
  86874. this.onBeforeRenderObservable = new BABYLON.Observable();
  86875. /**
  86876. * An event triggered after rendering the scene
  86877. * @type {BABYLON.Observable}
  86878. */
  86879. this.onAfterRenderObservable = new BABYLON.Observable();
  86880. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  86881. this.isBackground = isBackground === undefined ? true : isBackground;
  86882. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  86883. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  86884. this._scene.layers.push(this);
  86885. var engine = this._scene.getEngine();
  86886. // VBO
  86887. var vertices = [];
  86888. vertices.push(1, 1);
  86889. vertices.push(-1, 1);
  86890. vertices.push(-1, -1);
  86891. vertices.push(1, -1);
  86892. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86893. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86894. this._createIndexBuffer();
  86895. // Effects
  86896. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  86897. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  86898. }
  86899. Object.defineProperty(Layer.prototype, "onDispose", {
  86900. set: function (callback) {
  86901. if (this._onDisposeObserver) {
  86902. this.onDisposeObservable.remove(this._onDisposeObserver);
  86903. }
  86904. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  86905. },
  86906. enumerable: true,
  86907. configurable: true
  86908. });
  86909. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  86910. set: function (callback) {
  86911. if (this._onBeforeRenderObserver) {
  86912. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  86913. }
  86914. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  86915. },
  86916. enumerable: true,
  86917. configurable: true
  86918. });
  86919. Object.defineProperty(Layer.prototype, "onAfterRender", {
  86920. set: function (callback) {
  86921. if (this._onAfterRenderObserver) {
  86922. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86923. }
  86924. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  86925. },
  86926. enumerable: true,
  86927. configurable: true
  86928. });
  86929. Layer.prototype._createIndexBuffer = function () {
  86930. var engine = this._scene.getEngine();
  86931. // Indices
  86932. var indices = [];
  86933. indices.push(0);
  86934. indices.push(1);
  86935. indices.push(2);
  86936. indices.push(0);
  86937. indices.push(2);
  86938. indices.push(3);
  86939. this._indexBuffer = engine.createIndexBuffer(indices);
  86940. };
  86941. Layer.prototype._rebuild = function () {
  86942. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86943. if (vb) {
  86944. vb._rebuild();
  86945. }
  86946. this._createIndexBuffer();
  86947. };
  86948. Layer.prototype.render = function () {
  86949. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  86950. // Check
  86951. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  86952. return;
  86953. var engine = this._scene.getEngine();
  86954. this.onBeforeRenderObservable.notifyObservers(this);
  86955. // Render
  86956. engine.enableEffect(currentEffect);
  86957. engine.setState(false);
  86958. // Texture
  86959. currentEffect.setTexture("textureSampler", this.texture);
  86960. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  86961. // Color
  86962. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  86963. // Scale / offset
  86964. currentEffect.setVector2("offset", this.offset);
  86965. currentEffect.setVector2("scale", this.scale);
  86966. // VBOs
  86967. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86968. // Draw order
  86969. if (!this.alphaTest) {
  86970. engine.setAlphaMode(this.alphaBlendingMode);
  86971. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86972. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86973. }
  86974. else {
  86975. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86976. }
  86977. this.onAfterRenderObservable.notifyObservers(this);
  86978. };
  86979. Layer.prototype.dispose = function () {
  86980. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86981. if (vertexBuffer) {
  86982. vertexBuffer.dispose();
  86983. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86984. }
  86985. if (this._indexBuffer) {
  86986. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86987. this._indexBuffer = null;
  86988. }
  86989. if (this.texture) {
  86990. this.texture.dispose();
  86991. this.texture = null;
  86992. }
  86993. // Remove from scene
  86994. var index = this._scene.layers.indexOf(this);
  86995. this._scene.layers.splice(index, 1);
  86996. // Callback
  86997. this.onDisposeObservable.notifyObservers(this);
  86998. this.onDisposeObservable.clear();
  86999. this.onAfterRenderObservable.clear();
  87000. this.onBeforeRenderObservable.clear();
  87001. };
  87002. return Layer;
  87003. }());
  87004. BABYLON.Layer = Layer;
  87005. })(BABYLON || (BABYLON = {}));
  87006. //# sourceMappingURL=babylon.layer.js.map
  87007. var BABYLON;
  87008. (function (BABYLON) {
  87009. var TextureTools = /** @class */ (function () {
  87010. function TextureTools() {
  87011. }
  87012. /**
  87013. * Uses the GPU to create a copy texture rescaled at a given size
  87014. * @param texture Texture to copy from
  87015. * @param width Desired width
  87016. * @param height Desired height
  87017. * @return Generated texture
  87018. */
  87019. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  87020. if (useBilinearMode === void 0) { useBilinearMode = true; }
  87021. var scene = texture.getScene();
  87022. var engine = scene.getEngine();
  87023. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  87024. rtt.wrapU = texture.wrapU;
  87025. rtt.wrapV = texture.wrapV;
  87026. rtt.uOffset = texture.uOffset;
  87027. rtt.vOffset = texture.vOffset;
  87028. rtt.uScale = texture.uScale;
  87029. rtt.vScale = texture.vScale;
  87030. rtt.uAng = texture.uAng;
  87031. rtt.vAng = texture.vAng;
  87032. rtt.wAng = texture.wAng;
  87033. rtt.coordinatesIndex = texture.coordinatesIndex;
  87034. rtt.level = texture.level;
  87035. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  87036. rtt._texture.isReady = false;
  87037. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87038. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87039. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  87040. passPostProcess.getEffect().executeWhenCompiled(function () {
  87041. passPostProcess.onApply = function (effect) {
  87042. effect.setTexture("textureSampler", texture);
  87043. };
  87044. var internalTexture = rtt.getInternalTexture();
  87045. if (internalTexture) {
  87046. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  87047. engine.unBindFramebuffer(internalTexture);
  87048. rtt.disposeFramebufferObjects();
  87049. passPostProcess.dispose();
  87050. internalTexture.isReady = true;
  87051. }
  87052. });
  87053. return rtt;
  87054. };
  87055. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  87056. if (!scene._environmentBRDFTexture) {
  87057. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87058. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87059. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87060. scene._environmentBRDFTexture = texture;
  87061. }
  87062. return scene._environmentBRDFTexture;
  87063. };
  87064. 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=";
  87065. return TextureTools;
  87066. }());
  87067. BABYLON.TextureTools = TextureTools;
  87068. })(BABYLON || (BABYLON = {}));
  87069. //# sourceMappingURL=babylon.textureTools.js.map
  87070. var BABYLON;
  87071. (function (BABYLON) {
  87072. var FramingBehavior = /** @class */ (function () {
  87073. function FramingBehavior() {
  87074. this._mode = FramingBehavior.FitFrustumSidesMode;
  87075. this._radiusScale = 1.0;
  87076. this._positionScale = 0.5;
  87077. this._defaultElevation = 0.3;
  87078. this._elevationReturnTime = 1500;
  87079. this._elevationReturnWaitTime = 1000;
  87080. this._zoomStopsAnimation = false;
  87081. this._framingTime = 1500;
  87082. this._isPointerDown = false;
  87083. this._lastInteractionTime = -Infinity;
  87084. // Framing control
  87085. this._animatables = new Array();
  87086. this._betaIsAnimating = false;
  87087. }
  87088. Object.defineProperty(FramingBehavior.prototype, "name", {
  87089. get: function () {
  87090. return "Framing";
  87091. },
  87092. enumerable: true,
  87093. configurable: true
  87094. });
  87095. Object.defineProperty(FramingBehavior.prototype, "mode", {
  87096. /**
  87097. * Gets current mode used by the behavior.
  87098. */
  87099. get: function () {
  87100. return this._mode;
  87101. },
  87102. /**
  87103. * Sets the current mode used by the behavior
  87104. */
  87105. set: function (mode) {
  87106. this._mode = mode;
  87107. },
  87108. enumerable: true,
  87109. configurable: true
  87110. });
  87111. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  87112. /**
  87113. * Gets the scale applied to the radius
  87114. */
  87115. get: function () {
  87116. return this._radiusScale;
  87117. },
  87118. /**
  87119. * Sets the scale applied to the radius (1 by default)
  87120. */
  87121. set: function (radius) {
  87122. this._radiusScale = radius;
  87123. },
  87124. enumerable: true,
  87125. configurable: true
  87126. });
  87127. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  87128. /**
  87129. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87130. */
  87131. get: function () {
  87132. return this._positionScale;
  87133. },
  87134. /**
  87135. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87136. */
  87137. set: function (scale) {
  87138. this._positionScale = scale;
  87139. },
  87140. enumerable: true,
  87141. configurable: true
  87142. });
  87143. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  87144. /**
  87145. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87146. * behaviour is triggered, in radians.
  87147. */
  87148. get: function () {
  87149. return this._defaultElevation;
  87150. },
  87151. /**
  87152. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87153. * behaviour is triggered, in radians.
  87154. */
  87155. set: function (elevation) {
  87156. this._defaultElevation = elevation;
  87157. },
  87158. enumerable: true,
  87159. configurable: true
  87160. });
  87161. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  87162. /**
  87163. * Gets the time (in milliseconds) taken to return to the default beta position.
  87164. * Negative value indicates camera should not return to default.
  87165. */
  87166. get: function () {
  87167. return this._elevationReturnTime;
  87168. },
  87169. /**
  87170. * Sets the time (in milliseconds) taken to return to the default beta position.
  87171. * Negative value indicates camera should not return to default.
  87172. */
  87173. set: function (speed) {
  87174. this._elevationReturnTime = speed;
  87175. },
  87176. enumerable: true,
  87177. configurable: true
  87178. });
  87179. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  87180. /**
  87181. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87182. */
  87183. get: function () {
  87184. return this._elevationReturnWaitTime;
  87185. },
  87186. /**
  87187. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87188. */
  87189. set: function (time) {
  87190. this._elevationReturnWaitTime = time;
  87191. },
  87192. enumerable: true,
  87193. configurable: true
  87194. });
  87195. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  87196. /**
  87197. * Gets the flag that indicates if user zooming should stop animation.
  87198. */
  87199. get: function () {
  87200. return this._zoomStopsAnimation;
  87201. },
  87202. /**
  87203. * Sets the flag that indicates if user zooming should stop animation.
  87204. */
  87205. set: function (flag) {
  87206. this._zoomStopsAnimation = flag;
  87207. },
  87208. enumerable: true,
  87209. configurable: true
  87210. });
  87211. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  87212. /**
  87213. * Gets the transition time when framing the mesh, in milliseconds
  87214. */
  87215. get: function () {
  87216. return this._framingTime;
  87217. },
  87218. /**
  87219. * Sets the transition time when framing the mesh, in milliseconds
  87220. */
  87221. set: function (time) {
  87222. this._framingTime = time;
  87223. },
  87224. enumerable: true,
  87225. configurable: true
  87226. });
  87227. FramingBehavior.prototype.init = function () {
  87228. // Do notihng
  87229. };
  87230. FramingBehavior.prototype.attach = function (camera) {
  87231. var _this = this;
  87232. this._attachedCamera = camera;
  87233. var scene = this._attachedCamera.getScene();
  87234. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  87235. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87236. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87237. _this._isPointerDown = true;
  87238. return;
  87239. }
  87240. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87241. _this._isPointerDown = false;
  87242. }
  87243. });
  87244. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87245. if (mesh) {
  87246. _this.zoomOnMesh(mesh);
  87247. }
  87248. });
  87249. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87250. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87251. _this._applyUserInteraction();
  87252. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  87253. // back to the default position after a given timeout
  87254. _this._maintainCameraAboveGround();
  87255. });
  87256. };
  87257. FramingBehavior.prototype.detach = function () {
  87258. if (!this._attachedCamera) {
  87259. return;
  87260. }
  87261. var scene = this._attachedCamera.getScene();
  87262. if (this._onPrePointerObservableObserver) {
  87263. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87264. }
  87265. if (this._onAfterCheckInputsObserver) {
  87266. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87267. }
  87268. if (this._onMeshTargetChangedObserver) {
  87269. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87270. }
  87271. this._attachedCamera = null;
  87272. };
  87273. /**
  87274. * Targets the given mesh and updates zoom level accordingly.
  87275. * @param mesh The mesh to target.
  87276. * @param radius Optional. If a cached radius position already exists, overrides default.
  87277. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87278. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87279. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87280. */
  87281. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87282. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87283. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87284. mesh.computeWorldMatrix(true);
  87285. var boundingBox = mesh.getBoundingInfo().boundingBox;
  87286. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  87287. };
  87288. /**
  87289. * Targets the given mesh with its children and updates zoom level accordingly.
  87290. * @param mesh The mesh to target.
  87291. * @param radius Optional. If a cached radius position already exists, overrides default.
  87292. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87293. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87294. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87295. */
  87296. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  87297. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87298. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87299. mesh.computeWorldMatrix(true);
  87300. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  87301. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  87302. };
  87303. /**
  87304. * Targets the given meshes with their children and updates zoom level accordingly.
  87305. * @param meshes The mesh to target.
  87306. * @param radius Optional. If a cached radius position already exists, overrides default.
  87307. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87308. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87309. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87310. */
  87311. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  87312. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87313. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87314. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  87315. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  87316. for (var i = 0; i < meshes.length; i++) {
  87317. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  87318. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  87319. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  87320. }
  87321. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  87322. };
  87323. /**
  87324. * Targets the given mesh and updates zoom level accordingly.
  87325. * @param mesh The mesh to target.
  87326. * @param radius Optional. If a cached radius position already exists, overrides default.
  87327. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  87328. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  87329. * @param onAnimationEnd Callback triggered at the end of the framing animation
  87330. */
  87331. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  87332. var _this = this;
  87333. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  87334. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  87335. var zoomTarget;
  87336. if (!this._attachedCamera) {
  87337. return;
  87338. }
  87339. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  87340. var bottom = minimumWorld.y;
  87341. var top = maximumWorld.y;
  87342. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  87343. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  87344. if (focusOnOriginXZ) {
  87345. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  87346. }
  87347. else {
  87348. var centerWorld = minimumWorld.add(radiusWorld);
  87349. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  87350. }
  87351. if (!this._vectorTransition) {
  87352. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  87353. }
  87354. this._betaIsAnimating = true;
  87355. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  87356. if (animatable) {
  87357. this._animatables.push(animatable);
  87358. }
  87359. // sets the radius and lower radius bounds
  87360. // Small delta ensures camera is not always at lower zoom limit.
  87361. var radius = 0;
  87362. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  87363. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87364. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  87365. radius = position;
  87366. }
  87367. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87368. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  87369. if (this._attachedCamera.lowerRadiusLimit === null) {
  87370. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  87371. }
  87372. }
  87373. // Set sensibilities
  87374. var extend = maximumWorld.subtract(minimumWorld).length();
  87375. this._attachedCamera.panningSensibility = 5000 / extend;
  87376. this._attachedCamera.wheelPrecision = 100 / radius;
  87377. // transition to new radius
  87378. if (!this._radiusTransition) {
  87379. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87380. }
  87381. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  87382. _this.stopAllAnimations();
  87383. if (onAnimationEnd) {
  87384. onAnimationEnd();
  87385. }
  87386. if (_this._attachedCamera) {
  87387. _this._attachedCamera.storeState();
  87388. }
  87389. });
  87390. if (animatable) {
  87391. this._animatables.push(animatable);
  87392. }
  87393. };
  87394. /**
  87395. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  87396. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  87397. * frustum width.
  87398. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  87399. * to fully enclose the mesh in the viewing frustum.
  87400. */
  87401. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  87402. var size = maximumWorld.subtract(minimumWorld);
  87403. var boxVectorGlobalDiagonal = size.length();
  87404. var frustumSlope = this._getFrustumSlope();
  87405. // Formula for setting distance
  87406. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  87407. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  87408. // Horizon distance
  87409. var radius = radiusWithoutFraming * this._radiusScale;
  87410. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  87411. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  87412. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  87413. var camera = this._attachedCamera;
  87414. if (!camera) {
  87415. return 0;
  87416. }
  87417. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  87418. // Don't exceed the requested limit
  87419. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  87420. }
  87421. // Don't exceed the upper radius limit
  87422. if (camera.upperRadiusLimit) {
  87423. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  87424. }
  87425. return distance;
  87426. };
  87427. /**
  87428. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  87429. * is automatically returned to its default position (expected to be above ground plane).
  87430. */
  87431. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  87432. var _this = this;
  87433. if (this._elevationReturnTime < 0) {
  87434. return;
  87435. }
  87436. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  87437. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  87438. var limitBeta = Math.PI * 0.5;
  87439. // Bring the camera back up if below the ground plane
  87440. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  87441. this._betaIsAnimating = true;
  87442. //Transition to new position
  87443. this.stopAllAnimations();
  87444. if (!this._betaTransition) {
  87445. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  87446. }
  87447. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  87448. _this._clearAnimationLocks();
  87449. _this.stopAllAnimations();
  87450. });
  87451. if (animatabe) {
  87452. this._animatables.push(animatabe);
  87453. }
  87454. }
  87455. };
  87456. /**
  87457. * Returns the frustum slope based on the canvas ratio and camera FOV
  87458. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  87459. */
  87460. FramingBehavior.prototype._getFrustumSlope = function () {
  87461. // Calculate the viewport ratio
  87462. // Aspect Ratio is Height/Width.
  87463. var camera = this._attachedCamera;
  87464. if (!camera) {
  87465. return BABYLON.Vector2.Zero();
  87466. }
  87467. var engine = camera.getScene().getEngine();
  87468. var aspectRatio = engine.getAspectRatio(camera);
  87469. // Camera FOV is the vertical field of view (top-bottom) in radians.
  87470. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  87471. var frustumSlopeY = Math.tan(camera.fov / 2);
  87472. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  87473. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  87474. // along the forward vector.
  87475. var frustumSlopeX = frustumSlopeY * aspectRatio;
  87476. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  87477. };
  87478. /**
  87479. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  87480. */
  87481. FramingBehavior.prototype._clearAnimationLocks = function () {
  87482. this._betaIsAnimating = false;
  87483. };
  87484. /**
  87485. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87486. */
  87487. FramingBehavior.prototype._applyUserInteraction = function () {
  87488. if (this.isUserIsMoving) {
  87489. this._lastInteractionTime = BABYLON.Tools.Now;
  87490. this.stopAllAnimations();
  87491. this._clearAnimationLocks();
  87492. }
  87493. };
  87494. /**
  87495. * Stops and removes all animations that have been applied to the camera
  87496. */
  87497. FramingBehavior.prototype.stopAllAnimations = function () {
  87498. if (this._attachedCamera) {
  87499. this._attachedCamera.animations = [];
  87500. }
  87501. while (this._animatables.length) {
  87502. if (this._animatables[0]) {
  87503. this._animatables[0].onAnimationEnd = null;
  87504. this._animatables[0].stop();
  87505. }
  87506. this._animatables.shift();
  87507. }
  87508. };
  87509. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  87510. /**
  87511. * Gets a value indicating if the user is moving the camera
  87512. */
  87513. get: function () {
  87514. if (!this._attachedCamera) {
  87515. return false;
  87516. }
  87517. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87518. this._attachedCamera.inertialBetaOffset !== 0 ||
  87519. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87520. this._attachedCamera.inertialPanningX !== 0 ||
  87521. this._attachedCamera.inertialPanningY !== 0 ||
  87522. this._isPointerDown;
  87523. },
  87524. enumerable: true,
  87525. configurable: true
  87526. });
  87527. /**
  87528. * The easing function used by animations
  87529. */
  87530. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  87531. /**
  87532. * The easing mode used by animations
  87533. */
  87534. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  87535. // Statics
  87536. /**
  87537. * The camera can move all the way towards the mesh.
  87538. */
  87539. FramingBehavior.IgnoreBoundsSizeMode = 0;
  87540. /**
  87541. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  87542. */
  87543. FramingBehavior.FitFrustumSidesMode = 1;
  87544. return FramingBehavior;
  87545. }());
  87546. BABYLON.FramingBehavior = FramingBehavior;
  87547. })(BABYLON || (BABYLON = {}));
  87548. //# sourceMappingURL=babylon.framingBehavior.js.map
  87549. var BABYLON;
  87550. (function (BABYLON) {
  87551. /**
  87552. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  87553. */
  87554. var BouncingBehavior = /** @class */ (function () {
  87555. function BouncingBehavior() {
  87556. /**
  87557. * The duration of the animation, in milliseconds
  87558. */
  87559. this.transitionDuration = 450;
  87560. /**
  87561. * Length of the distance animated by the transition when lower radius is reached
  87562. */
  87563. this.lowerRadiusTransitionRange = 2;
  87564. /**
  87565. * Length of the distance animated by the transition when upper radius is reached
  87566. */
  87567. this.upperRadiusTransitionRange = -2;
  87568. this._autoTransitionRange = false;
  87569. // Animations
  87570. this._radiusIsAnimating = false;
  87571. this._radiusBounceTransition = null;
  87572. this._animatables = new Array();
  87573. }
  87574. Object.defineProperty(BouncingBehavior.prototype, "name", {
  87575. get: function () {
  87576. return "Bouncing";
  87577. },
  87578. enumerable: true,
  87579. configurable: true
  87580. });
  87581. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  87582. /**
  87583. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87584. */
  87585. get: function () {
  87586. return this._autoTransitionRange;
  87587. },
  87588. /**
  87589. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87590. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  87591. */
  87592. set: function (value) {
  87593. var _this = this;
  87594. if (this._autoTransitionRange === value) {
  87595. return;
  87596. }
  87597. this._autoTransitionRange = value;
  87598. var camera = this._attachedCamera;
  87599. if (!camera) {
  87600. return;
  87601. }
  87602. if (value) {
  87603. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87604. if (!mesh) {
  87605. return;
  87606. }
  87607. mesh.computeWorldMatrix(true);
  87608. var diagonal = mesh.getBoundingInfo().diagonalLength;
  87609. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  87610. _this.upperRadiusTransitionRange = diagonal * 0.05;
  87611. });
  87612. }
  87613. else if (this._onMeshTargetChangedObserver) {
  87614. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87615. }
  87616. },
  87617. enumerable: true,
  87618. configurable: true
  87619. });
  87620. BouncingBehavior.prototype.init = function () {
  87621. // Do notihng
  87622. };
  87623. BouncingBehavior.prototype.attach = function (camera) {
  87624. var _this = this;
  87625. this._attachedCamera = camera;
  87626. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87627. if (!_this._attachedCamera) {
  87628. return;
  87629. }
  87630. // Add the bounce animation to the lower radius limit
  87631. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  87632. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  87633. }
  87634. // Add the bounce animation to the upper radius limit
  87635. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  87636. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  87637. }
  87638. });
  87639. };
  87640. BouncingBehavior.prototype.detach = function () {
  87641. if (!this._attachedCamera) {
  87642. return;
  87643. }
  87644. if (this._onAfterCheckInputsObserver) {
  87645. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87646. }
  87647. if (this._onMeshTargetChangedObserver) {
  87648. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87649. }
  87650. this._attachedCamera = null;
  87651. };
  87652. /**
  87653. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  87654. * @param radiusLimit The limit to check against.
  87655. * @return Bool to indicate if at limit.
  87656. */
  87657. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  87658. if (!this._attachedCamera) {
  87659. return false;
  87660. }
  87661. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  87662. return true;
  87663. }
  87664. return false;
  87665. };
  87666. /**
  87667. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  87668. * @param radiusDelta The delta by which to animate to. Can be negative.
  87669. */
  87670. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  87671. var _this = this;
  87672. if (!this._attachedCamera) {
  87673. return;
  87674. }
  87675. if (!this._radiusBounceTransition) {
  87676. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  87677. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  87678. }
  87679. // Prevent zoom until bounce has completed
  87680. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  87681. this._attachedCamera.wheelPrecision = Infinity;
  87682. this._attachedCamera.inertialRadiusOffset = 0;
  87683. // Animate to the radius limit
  87684. this.stopAllAnimations();
  87685. this._radiusIsAnimating = true;
  87686. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  87687. if (animatable) {
  87688. this._animatables.push(animatable);
  87689. }
  87690. };
  87691. /**
  87692. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  87693. */
  87694. BouncingBehavior.prototype._clearAnimationLocks = function () {
  87695. this._radiusIsAnimating = false;
  87696. if (this._attachedCamera) {
  87697. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  87698. }
  87699. };
  87700. /**
  87701. * Stops and removes all animations that have been applied to the camera
  87702. */
  87703. BouncingBehavior.prototype.stopAllAnimations = function () {
  87704. if (this._attachedCamera) {
  87705. this._attachedCamera.animations = [];
  87706. }
  87707. while (this._animatables.length) {
  87708. this._animatables[0].onAnimationEnd = null;
  87709. this._animatables[0].stop();
  87710. this._animatables.shift();
  87711. }
  87712. };
  87713. /**
  87714. * The easing function used by animations
  87715. */
  87716. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  87717. /**
  87718. * The easing mode used by animations
  87719. */
  87720. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  87721. return BouncingBehavior;
  87722. }());
  87723. BABYLON.BouncingBehavior = BouncingBehavior;
  87724. })(BABYLON || (BABYLON = {}));
  87725. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  87726. var BABYLON;
  87727. (function (BABYLON) {
  87728. var AutoRotationBehavior = /** @class */ (function () {
  87729. function AutoRotationBehavior() {
  87730. this._zoomStopsAnimation = false;
  87731. this._idleRotationSpeed = 0.05;
  87732. this._idleRotationWaitTime = 2000;
  87733. this._idleRotationSpinupTime = 2000;
  87734. this._isPointerDown = false;
  87735. this._lastFrameTime = null;
  87736. this._lastInteractionTime = -Infinity;
  87737. this._cameraRotationSpeed = 0;
  87738. this._lastFrameRadius = 0;
  87739. }
  87740. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  87741. get: function () {
  87742. return "AutoRotation";
  87743. },
  87744. enumerable: true,
  87745. configurable: true
  87746. });
  87747. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  87748. /**
  87749. * Gets the flag that indicates if user zooming should stop animation.
  87750. */
  87751. get: function () {
  87752. return this._zoomStopsAnimation;
  87753. },
  87754. /**
  87755. * Sets the flag that indicates if user zooming should stop animation.
  87756. */
  87757. set: function (flag) {
  87758. this._zoomStopsAnimation = flag;
  87759. },
  87760. enumerable: true,
  87761. configurable: true
  87762. });
  87763. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  87764. /**
  87765. * Gets the default speed at which the camera rotates around the model.
  87766. */
  87767. get: function () {
  87768. return this._idleRotationSpeed;
  87769. },
  87770. /**
  87771. * Sets the default speed at which the camera rotates around the model.
  87772. */
  87773. set: function (speed) {
  87774. this._idleRotationSpeed = speed;
  87775. },
  87776. enumerable: true,
  87777. configurable: true
  87778. });
  87779. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  87780. /**
  87781. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  87782. */
  87783. get: function () {
  87784. return this._idleRotationWaitTime;
  87785. },
  87786. /**
  87787. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  87788. */
  87789. set: function (time) {
  87790. this._idleRotationWaitTime = time;
  87791. },
  87792. enumerable: true,
  87793. configurable: true
  87794. });
  87795. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  87796. /**
  87797. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87798. */
  87799. get: function () {
  87800. return this._idleRotationSpinupTime;
  87801. },
  87802. /**
  87803. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87804. */
  87805. set: function (time) {
  87806. this._idleRotationSpinupTime = time;
  87807. },
  87808. enumerable: true,
  87809. configurable: true
  87810. });
  87811. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  87812. /**
  87813. * Gets a value indicating if the camera is currently rotating because of this behavior
  87814. */
  87815. get: function () {
  87816. return Math.abs(this._cameraRotationSpeed) > 0;
  87817. },
  87818. enumerable: true,
  87819. configurable: true
  87820. });
  87821. AutoRotationBehavior.prototype.init = function () {
  87822. // Do notihng
  87823. };
  87824. AutoRotationBehavior.prototype.attach = function (camera) {
  87825. var _this = this;
  87826. this._attachedCamera = camera;
  87827. var scene = this._attachedCamera.getScene();
  87828. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87829. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87830. _this._isPointerDown = true;
  87831. return;
  87832. }
  87833. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87834. _this._isPointerDown = false;
  87835. }
  87836. });
  87837. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87838. var now = BABYLON.Tools.Now;
  87839. var dt = 0;
  87840. if (_this._lastFrameTime != null) {
  87841. dt = now - _this._lastFrameTime;
  87842. }
  87843. _this._lastFrameTime = now;
  87844. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87845. _this._applyUserInteraction();
  87846. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  87847. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  87848. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  87849. // Step camera rotation by rotation speed
  87850. if (_this._attachedCamera) {
  87851. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  87852. }
  87853. });
  87854. };
  87855. AutoRotationBehavior.prototype.detach = function () {
  87856. if (!this._attachedCamera) {
  87857. return;
  87858. }
  87859. var scene = this._attachedCamera.getScene();
  87860. if (this._onPrePointerObservableObserver) {
  87861. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87862. }
  87863. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87864. this._attachedCamera = null;
  87865. };
  87866. /**
  87867. * Returns true if user is scrolling.
  87868. * @return true if user is scrolling.
  87869. */
  87870. AutoRotationBehavior.prototype._userIsZooming = function () {
  87871. if (!this._attachedCamera) {
  87872. return false;
  87873. }
  87874. return this._attachedCamera.inertialRadiusOffset !== 0;
  87875. };
  87876. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  87877. if (!this._attachedCamera) {
  87878. return false;
  87879. }
  87880. var zoomHasHitLimit = false;
  87881. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  87882. zoomHasHitLimit = true;
  87883. }
  87884. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  87885. this._lastFrameRadius = this._attachedCamera.radius;
  87886. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  87887. };
  87888. /**
  87889. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87890. */
  87891. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  87892. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  87893. this._lastInteractionTime = BABYLON.Tools.Now;
  87894. }
  87895. };
  87896. // Tools
  87897. AutoRotationBehavior.prototype._userIsMoving = function () {
  87898. if (!this._attachedCamera) {
  87899. return false;
  87900. }
  87901. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87902. this._attachedCamera.inertialBetaOffset !== 0 ||
  87903. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87904. this._attachedCamera.inertialPanningX !== 0 ||
  87905. this._attachedCamera.inertialPanningY !== 0 ||
  87906. this._isPointerDown;
  87907. };
  87908. return AutoRotationBehavior;
  87909. }());
  87910. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  87911. })(BABYLON || (BABYLON = {}));
  87912. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  87913. var BABYLON;
  87914. (function (BABYLON) {
  87915. /**
  87916. * This class can be used to get instrumentation data from a Babylon engine
  87917. */
  87918. var EngineInstrumentation = /** @class */ (function () {
  87919. function EngineInstrumentation(engine) {
  87920. this.engine = engine;
  87921. this._captureGPUFrameTime = false;
  87922. this._gpuFrameTime = new BABYLON.PerfCounter();
  87923. this._captureShaderCompilationTime = false;
  87924. this._shaderCompilationTime = new BABYLON.PerfCounter();
  87925. // Observers
  87926. this._onBeginFrameObserver = null;
  87927. this._onEndFrameObserver = null;
  87928. this._onBeforeShaderCompilationObserver = null;
  87929. this._onAfterShaderCompilationObserver = null;
  87930. }
  87931. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  87932. // Properties
  87933. /**
  87934. * Gets the perf counter used for GPU frame time
  87935. */
  87936. get: function () {
  87937. return this._gpuFrameTime;
  87938. },
  87939. enumerable: true,
  87940. configurable: true
  87941. });
  87942. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  87943. /**
  87944. * Gets the GPU frame time capture status
  87945. */
  87946. get: function () {
  87947. return this._captureGPUFrameTime;
  87948. },
  87949. /**
  87950. * Enable or disable the GPU frame time capture
  87951. */
  87952. set: function (value) {
  87953. var _this = this;
  87954. if (value === this._captureGPUFrameTime) {
  87955. return;
  87956. }
  87957. this._captureGPUFrameTime = value;
  87958. if (value) {
  87959. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  87960. if (!_this._gpuFrameTimeToken) {
  87961. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  87962. }
  87963. });
  87964. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  87965. if (!_this._gpuFrameTimeToken) {
  87966. return;
  87967. }
  87968. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  87969. if (time > -1) {
  87970. _this._gpuFrameTimeToken = null;
  87971. _this._gpuFrameTime.fetchNewFrame();
  87972. _this._gpuFrameTime.addCount(time, true);
  87973. }
  87974. });
  87975. }
  87976. else {
  87977. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87978. this._onBeginFrameObserver = null;
  87979. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87980. this._onEndFrameObserver = null;
  87981. }
  87982. },
  87983. enumerable: true,
  87984. configurable: true
  87985. });
  87986. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  87987. /**
  87988. * Gets the perf counter used for shader compilation time
  87989. */
  87990. get: function () {
  87991. return this._shaderCompilationTime;
  87992. },
  87993. enumerable: true,
  87994. configurable: true
  87995. });
  87996. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  87997. /**
  87998. * Gets the shader compilation time capture status
  87999. */
  88000. get: function () {
  88001. return this._captureShaderCompilationTime;
  88002. },
  88003. /**
  88004. * Enable or disable the shader compilation time capture
  88005. */
  88006. set: function (value) {
  88007. var _this = this;
  88008. if (value === this._captureShaderCompilationTime) {
  88009. return;
  88010. }
  88011. this._captureShaderCompilationTime = value;
  88012. if (value) {
  88013. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  88014. _this._shaderCompilationTime.fetchNewFrame();
  88015. _this._shaderCompilationTime.beginMonitoring();
  88016. });
  88017. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  88018. _this._shaderCompilationTime.endMonitoring();
  88019. });
  88020. }
  88021. else {
  88022. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88023. this._onBeforeShaderCompilationObserver = null;
  88024. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88025. this._onAfterShaderCompilationObserver = null;
  88026. }
  88027. },
  88028. enumerable: true,
  88029. configurable: true
  88030. });
  88031. EngineInstrumentation.prototype.dispose = function () {
  88032. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  88033. this._onBeginFrameObserver = null;
  88034. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  88035. this._onEndFrameObserver = null;
  88036. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  88037. this._onBeforeShaderCompilationObserver = null;
  88038. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  88039. this._onAfterShaderCompilationObserver = null;
  88040. this.engine = null;
  88041. };
  88042. return EngineInstrumentation;
  88043. }());
  88044. BABYLON.EngineInstrumentation = EngineInstrumentation;
  88045. })(BABYLON || (BABYLON = {}));
  88046. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  88047. var BABYLON;
  88048. (function (BABYLON) {
  88049. /**
  88050. * This class can be used to get instrumentation data from a Babylon engine
  88051. */
  88052. var SceneInstrumentation = /** @class */ (function () {
  88053. function SceneInstrumentation(scene) {
  88054. var _this = this;
  88055. this.scene = scene;
  88056. this._captureActiveMeshesEvaluationTime = false;
  88057. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  88058. this._captureRenderTargetsRenderTime = false;
  88059. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  88060. this._captureFrameTime = false;
  88061. this._frameTime = new BABYLON.PerfCounter();
  88062. this._captureRenderTime = false;
  88063. this._renderTime = new BABYLON.PerfCounter();
  88064. this._captureInterFrameTime = false;
  88065. this._interFrameTime = new BABYLON.PerfCounter();
  88066. this._captureParticlesRenderTime = false;
  88067. this._particlesRenderTime = new BABYLON.PerfCounter();
  88068. this._captureSpritesRenderTime = false;
  88069. this._spritesRenderTime = new BABYLON.PerfCounter();
  88070. this._capturePhysicsTime = false;
  88071. this._physicsTime = new BABYLON.PerfCounter();
  88072. this._captureAnimationsTime = false;
  88073. this._animationsTime = new BABYLON.PerfCounter();
  88074. // Observers
  88075. this._onBeforeActiveMeshesEvaluationObserver = null;
  88076. this._onAfterActiveMeshesEvaluationObserver = null;
  88077. this._onBeforeRenderTargetsRenderObserver = null;
  88078. this._onAfterRenderTargetsRenderObserver = null;
  88079. this._onAfterRenderObserver = null;
  88080. this._onBeforeDrawPhaseObserver = null;
  88081. this._onAfterDrawPhaseObserver = null;
  88082. this._onBeforeAnimationsObserver = null;
  88083. this._onBeforeParticlesRenderingObserver = null;
  88084. this._onAfterParticlesRenderingObserver = null;
  88085. this._onBeforeSpritesRenderingObserver = null;
  88086. this._onAfterSpritesRenderingObserver = null;
  88087. this._onBeforePhysicsObserver = null;
  88088. this._onAfterPhysicsObserver = null;
  88089. this._onAfterAnimationsObserver = null;
  88090. // Before render
  88091. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  88092. if (_this._captureActiveMeshesEvaluationTime) {
  88093. _this._activeMeshesEvaluationTime.fetchNewFrame();
  88094. }
  88095. if (_this._captureRenderTargetsRenderTime) {
  88096. _this._renderTargetsRenderTime.fetchNewFrame();
  88097. }
  88098. if (_this._captureFrameTime) {
  88099. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  88100. _this._frameTime.beginMonitoring();
  88101. }
  88102. if (_this._captureInterFrameTime) {
  88103. _this._interFrameTime.endMonitoring();
  88104. }
  88105. if (_this._captureParticlesRenderTime) {
  88106. _this._particlesRenderTime.fetchNewFrame();
  88107. }
  88108. if (_this._captureSpritesRenderTime) {
  88109. _this._spritesRenderTime.fetchNewFrame();
  88110. }
  88111. if (_this._captureAnimationsTime) {
  88112. _this._animationsTime.beginMonitoring();
  88113. }
  88114. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  88115. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  88116. });
  88117. // After render
  88118. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  88119. if (_this._captureFrameTime) {
  88120. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  88121. _this._frameTime.endMonitoring();
  88122. }
  88123. if (_this._captureRenderTime) {
  88124. _this._renderTime.endMonitoring(false);
  88125. }
  88126. if (_this._captureInterFrameTime) {
  88127. _this._interFrameTime.beginMonitoring();
  88128. }
  88129. });
  88130. }
  88131. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  88132. // Properties
  88133. /**
  88134. * Gets the perf counter used for active meshes evaluation time
  88135. */
  88136. get: function () {
  88137. return this._activeMeshesEvaluationTime;
  88138. },
  88139. enumerable: true,
  88140. configurable: true
  88141. });
  88142. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  88143. /**
  88144. * Gets the active meshes evaluation time capture status
  88145. */
  88146. get: function () {
  88147. return this._captureActiveMeshesEvaluationTime;
  88148. },
  88149. /**
  88150. * Enable or disable the active meshes evaluation time capture
  88151. */
  88152. set: function (value) {
  88153. var _this = this;
  88154. if (value === this._captureActiveMeshesEvaluationTime) {
  88155. return;
  88156. }
  88157. this._captureActiveMeshesEvaluationTime = value;
  88158. if (value) {
  88159. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  88160. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  88161. _this._activeMeshesEvaluationTime.beginMonitoring();
  88162. });
  88163. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  88164. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  88165. _this._activeMeshesEvaluationTime.endMonitoring();
  88166. });
  88167. }
  88168. else {
  88169. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  88170. this._onBeforeActiveMeshesEvaluationObserver = null;
  88171. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  88172. this._onAfterActiveMeshesEvaluationObserver = null;
  88173. }
  88174. },
  88175. enumerable: true,
  88176. configurable: true
  88177. });
  88178. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  88179. /**
  88180. * Gets the perf counter used for render targets render time
  88181. */
  88182. get: function () {
  88183. return this._renderTargetsRenderTime;
  88184. },
  88185. enumerable: true,
  88186. configurable: true
  88187. });
  88188. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  88189. /**
  88190. * Gets the render targets render time capture status
  88191. */
  88192. get: function () {
  88193. return this._captureRenderTargetsRenderTime;
  88194. },
  88195. /**
  88196. * Enable or disable the render targets render time capture
  88197. */
  88198. set: function (value) {
  88199. var _this = this;
  88200. if (value === this._captureRenderTargetsRenderTime) {
  88201. return;
  88202. }
  88203. this._captureRenderTargetsRenderTime = value;
  88204. if (value) {
  88205. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  88206. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  88207. _this._renderTargetsRenderTime.beginMonitoring();
  88208. });
  88209. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  88210. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  88211. _this._renderTargetsRenderTime.endMonitoring(false);
  88212. });
  88213. }
  88214. else {
  88215. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  88216. this._onBeforeRenderTargetsRenderObserver = null;
  88217. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  88218. this._onAfterRenderTargetsRenderObserver = null;
  88219. }
  88220. },
  88221. enumerable: true,
  88222. configurable: true
  88223. });
  88224. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  88225. /**
  88226. * Gets the perf counter used for particles render time
  88227. */
  88228. get: function () {
  88229. return this._particlesRenderTime;
  88230. },
  88231. enumerable: true,
  88232. configurable: true
  88233. });
  88234. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  88235. /**
  88236. * Gets the particles render time capture status
  88237. */
  88238. get: function () {
  88239. return this._captureParticlesRenderTime;
  88240. },
  88241. /**
  88242. * Enable or disable the particles render time capture
  88243. */
  88244. set: function (value) {
  88245. var _this = this;
  88246. if (value === this._captureParticlesRenderTime) {
  88247. return;
  88248. }
  88249. this._captureParticlesRenderTime = value;
  88250. if (value) {
  88251. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  88252. BABYLON.Tools.StartPerformanceCounter("Particles");
  88253. _this._particlesRenderTime.beginMonitoring();
  88254. });
  88255. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  88256. BABYLON.Tools.EndPerformanceCounter("Particles");
  88257. _this._particlesRenderTime.endMonitoring(false);
  88258. });
  88259. }
  88260. else {
  88261. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  88262. this._onBeforeParticlesRenderingObserver = null;
  88263. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  88264. this._onAfterParticlesRenderingObserver = null;
  88265. }
  88266. },
  88267. enumerable: true,
  88268. configurable: true
  88269. });
  88270. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  88271. /**
  88272. * Gets the perf counter used for sprites render time
  88273. */
  88274. get: function () {
  88275. return this._spritesRenderTime;
  88276. },
  88277. enumerable: true,
  88278. configurable: true
  88279. });
  88280. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  88281. /**
  88282. * Gets the sprites render time capture status
  88283. */
  88284. get: function () {
  88285. return this._captureSpritesRenderTime;
  88286. },
  88287. /**
  88288. * Enable or disable the sprites render time capture
  88289. */
  88290. set: function (value) {
  88291. var _this = this;
  88292. if (value === this._captureSpritesRenderTime) {
  88293. return;
  88294. }
  88295. this._captureSpritesRenderTime = value;
  88296. if (value) {
  88297. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  88298. BABYLON.Tools.StartPerformanceCounter("Sprites");
  88299. _this._spritesRenderTime.beginMonitoring();
  88300. });
  88301. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  88302. BABYLON.Tools.EndPerformanceCounter("Sprites");
  88303. _this._spritesRenderTime.endMonitoring(false);
  88304. });
  88305. }
  88306. else {
  88307. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  88308. this._onBeforeSpritesRenderingObserver = null;
  88309. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88310. this._onAfterSpritesRenderingObserver = null;
  88311. }
  88312. },
  88313. enumerable: true,
  88314. configurable: true
  88315. });
  88316. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  88317. /**
  88318. * Gets the perf counter used for physics time
  88319. */
  88320. get: function () {
  88321. return this._physicsTime;
  88322. },
  88323. enumerable: true,
  88324. configurable: true
  88325. });
  88326. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  88327. /**
  88328. * Gets the physics time capture status
  88329. */
  88330. get: function () {
  88331. return this._capturePhysicsTime;
  88332. },
  88333. /**
  88334. * Enable or disable the physics time capture
  88335. */
  88336. set: function (value) {
  88337. var _this = this;
  88338. if (value === this._capturePhysicsTime) {
  88339. return;
  88340. }
  88341. this._capturePhysicsTime = value;
  88342. if (value) {
  88343. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  88344. BABYLON.Tools.StartPerformanceCounter("Physics");
  88345. _this._physicsTime.beginMonitoring();
  88346. });
  88347. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  88348. BABYLON.Tools.EndPerformanceCounter("Physics");
  88349. _this._physicsTime.endMonitoring();
  88350. });
  88351. }
  88352. else {
  88353. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88354. this._onBeforePhysicsObserver = null;
  88355. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88356. this._onAfterPhysicsObserver = null;
  88357. }
  88358. },
  88359. enumerable: true,
  88360. configurable: true
  88361. });
  88362. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  88363. /**
  88364. * Gets the perf counter used for animations time
  88365. */
  88366. get: function () {
  88367. return this._animationsTime;
  88368. },
  88369. enumerable: true,
  88370. configurable: true
  88371. });
  88372. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  88373. /**
  88374. * Gets the animations time capture status
  88375. */
  88376. get: function () {
  88377. return this._captureAnimationsTime;
  88378. },
  88379. /**
  88380. * Enable or disable the animations time capture
  88381. */
  88382. set: function (value) {
  88383. var _this = this;
  88384. if (value === this._captureAnimationsTime) {
  88385. return;
  88386. }
  88387. this._captureAnimationsTime = value;
  88388. if (value) {
  88389. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  88390. _this._animationsTime.endMonitoring();
  88391. });
  88392. }
  88393. else {
  88394. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88395. this._onAfterAnimationsObserver = null;
  88396. }
  88397. },
  88398. enumerable: true,
  88399. configurable: true
  88400. });
  88401. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  88402. /**
  88403. * Gets the perf counter used for frame time capture
  88404. */
  88405. get: function () {
  88406. return this._frameTime;
  88407. },
  88408. enumerable: true,
  88409. configurable: true
  88410. });
  88411. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  88412. /**
  88413. * Gets the frame time capture status
  88414. */
  88415. get: function () {
  88416. return this._captureFrameTime;
  88417. },
  88418. /**
  88419. * Enable or disable the frame time capture
  88420. */
  88421. set: function (value) {
  88422. this._captureFrameTime = value;
  88423. },
  88424. enumerable: true,
  88425. configurable: true
  88426. });
  88427. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  88428. /**
  88429. * Gets the perf counter used for inter-frames time capture
  88430. */
  88431. get: function () {
  88432. return this._interFrameTime;
  88433. },
  88434. enumerable: true,
  88435. configurable: true
  88436. });
  88437. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  88438. /**
  88439. * Gets the inter-frames time capture status
  88440. */
  88441. get: function () {
  88442. return this._captureInterFrameTime;
  88443. },
  88444. /**
  88445. * Enable or disable the inter-frames time capture
  88446. */
  88447. set: function (value) {
  88448. this._captureInterFrameTime = value;
  88449. },
  88450. enumerable: true,
  88451. configurable: true
  88452. });
  88453. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  88454. /**
  88455. * Gets the perf counter used for render time capture
  88456. */
  88457. get: function () {
  88458. return this._renderTime;
  88459. },
  88460. enumerable: true,
  88461. configurable: true
  88462. });
  88463. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  88464. /**
  88465. * Gets the render time capture status
  88466. */
  88467. get: function () {
  88468. return this._captureRenderTime;
  88469. },
  88470. /**
  88471. * Enable or disable the render time capture
  88472. */
  88473. set: function (value) {
  88474. var _this = this;
  88475. if (value === this._captureRenderTime) {
  88476. return;
  88477. }
  88478. this._captureRenderTime = value;
  88479. if (value) {
  88480. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  88481. _this._renderTime.beginMonitoring();
  88482. BABYLON.Tools.StartPerformanceCounter("Main render");
  88483. });
  88484. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  88485. _this._renderTime.endMonitoring(false);
  88486. BABYLON.Tools.EndPerformanceCounter("Main render");
  88487. });
  88488. }
  88489. else {
  88490. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88491. this._onBeforeDrawPhaseObserver = null;
  88492. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88493. this._onAfterDrawPhaseObserver = null;
  88494. }
  88495. },
  88496. enumerable: true,
  88497. configurable: true
  88498. });
  88499. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  88500. /**
  88501. * Gets the perf counter used for draw calls
  88502. */
  88503. get: function () {
  88504. return this.scene.getEngine()._drawCalls;
  88505. },
  88506. enumerable: true,
  88507. configurable: true
  88508. });
  88509. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  88510. /**
  88511. * Gets the perf counter used for texture collisions
  88512. */
  88513. get: function () {
  88514. return this.scene.getEngine()._textureCollisions;
  88515. },
  88516. enumerable: true,
  88517. configurable: true
  88518. });
  88519. SceneInstrumentation.prototype.dispose = function () {
  88520. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88521. this._onAfterRenderObserver = null;
  88522. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  88523. this._onBeforeActiveMeshesEvaluationObserver = null;
  88524. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  88525. this._onAfterActiveMeshesEvaluationObserver = null;
  88526. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  88527. this._onBeforeRenderTargetsRenderObserver = null;
  88528. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  88529. this._onAfterRenderTargetsRenderObserver = null;
  88530. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  88531. this._onBeforeAnimationsObserver = null;
  88532. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  88533. this._onBeforeParticlesRenderingObserver = null;
  88534. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  88535. this._onAfterParticlesRenderingObserver = null;
  88536. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  88537. this._onBeforeSpritesRenderingObserver = null;
  88538. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88539. this._onAfterSpritesRenderingObserver = null;
  88540. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88541. this._onBeforeDrawPhaseObserver = null;
  88542. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88543. this._onAfterDrawPhaseObserver = null;
  88544. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88545. this._onBeforePhysicsObserver = null;
  88546. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88547. this._onAfterPhysicsObserver = null;
  88548. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88549. this._onAfterAnimationsObserver = null;
  88550. this.scene = null;
  88551. };
  88552. return SceneInstrumentation;
  88553. }());
  88554. BABYLON.SceneInstrumentation = SceneInstrumentation;
  88555. })(BABYLON || (BABYLON = {}));
  88556. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  88557. var BABYLON;
  88558. (function (BABYLON) {
  88559. var _TimeToken = /** @class */ (function () {
  88560. function _TimeToken() {
  88561. this._timeElapsedQueryEnded = false;
  88562. }
  88563. return _TimeToken;
  88564. }());
  88565. BABYLON._TimeToken = _TimeToken;
  88566. })(BABYLON || (BABYLON = {}));
  88567. //# sourceMappingURL=babylon.timeToken.js.map
  88568. var BABYLON;
  88569. (function (BABYLON) {
  88570. /**
  88571. * Background material defines definition.
  88572. * @ignore Mainly internal Use
  88573. */
  88574. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  88575. __extends(BackgroundMaterialDefines, _super);
  88576. /**
  88577. * Constructor of the defines.
  88578. */
  88579. function BackgroundMaterialDefines() {
  88580. var _this = _super.call(this) || this;
  88581. /**
  88582. * True if the diffuse texture is in use.
  88583. */
  88584. _this.DIFFUSE = false;
  88585. /**
  88586. * The direct UV channel to use.
  88587. */
  88588. _this.DIFFUSEDIRECTUV = 0;
  88589. /**
  88590. * True if the diffuse texture is in gamma space.
  88591. */
  88592. _this.GAMMADIFFUSE = false;
  88593. /**
  88594. * True if the diffuse texture has opacity in the alpha channel.
  88595. */
  88596. _this.DIFFUSEHASALPHA = false;
  88597. /**
  88598. * True if you want the material to fade to transparent at grazing angle.
  88599. */
  88600. _this.OPACITYFRESNEL = false;
  88601. /**
  88602. * True if an extra blur needs to be added in the reflection.
  88603. */
  88604. _this.REFLECTIONBLUR = false;
  88605. /**
  88606. * True if you want the material to fade to reflection at grazing angle.
  88607. */
  88608. _this.REFLECTIONFRESNEL = false;
  88609. /**
  88610. * True if you want the material to falloff as far as you move away from the scene center.
  88611. */
  88612. _this.REFLECTIONFALLOFF = false;
  88613. /**
  88614. * False if the current Webgl implementation does not support the texture lod extension.
  88615. */
  88616. _this.TEXTURELODSUPPORT = false;
  88617. /**
  88618. * True to ensure the data are premultiplied.
  88619. */
  88620. _this.PREMULTIPLYALPHA = false;
  88621. /**
  88622. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  88623. */
  88624. _this.USERGBCOLOR = false;
  88625. /**
  88626. * True to add noise in order to reduce the banding effect.
  88627. */
  88628. _this.NOISE = false;
  88629. /**
  88630. * is the reflection texture in BGR color scheme?
  88631. * Mainly used to solve a bug in ios10 video tag
  88632. */
  88633. _this.REFLECTIONBGR = false;
  88634. _this.IMAGEPROCESSING = false;
  88635. _this.VIGNETTE = false;
  88636. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  88637. _this.VIGNETTEBLENDMODEOPAQUE = false;
  88638. _this.TONEMAPPING = false;
  88639. _this.CONTRAST = false;
  88640. _this.COLORCURVES = false;
  88641. _this.COLORGRADING = false;
  88642. _this.COLORGRADING3D = false;
  88643. _this.SAMPLER3DGREENDEPTH = false;
  88644. _this.SAMPLER3DBGRMAP = false;
  88645. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  88646. _this.EXPOSURE = false;
  88647. _this.GRAIN = false;
  88648. // Reflection.
  88649. _this.REFLECTION = false;
  88650. _this.REFLECTIONMAP_3D = false;
  88651. _this.REFLECTIONMAP_SPHERICAL = false;
  88652. _this.REFLECTIONMAP_PLANAR = false;
  88653. _this.REFLECTIONMAP_CUBIC = false;
  88654. _this.REFLECTIONMAP_PROJECTION = false;
  88655. _this.REFLECTIONMAP_SKYBOX = false;
  88656. _this.REFLECTIONMAP_EXPLICIT = false;
  88657. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88658. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88659. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88660. _this.INVERTCUBICMAP = false;
  88661. _this.REFLECTIONMAP_OPPOSITEZ = false;
  88662. _this.LODINREFLECTIONALPHA = false;
  88663. _this.GAMMAREFLECTION = false;
  88664. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  88665. // Default BJS.
  88666. _this.MAINUV1 = false;
  88667. _this.MAINUV2 = false;
  88668. _this.UV1 = false;
  88669. _this.UV2 = false;
  88670. _this.CLIPPLANE = false;
  88671. _this.POINTSIZE = false;
  88672. _this.FOG = false;
  88673. _this.NORMAL = false;
  88674. _this.NUM_BONE_INFLUENCERS = 0;
  88675. _this.BonesPerMesh = 0;
  88676. _this.INSTANCES = false;
  88677. _this.SHADOWFLOAT = false;
  88678. _this.rebuild();
  88679. return _this;
  88680. }
  88681. return BackgroundMaterialDefines;
  88682. }(BABYLON.MaterialDefines));
  88683. /**
  88684. * Background material used to create an efficient environement around your scene.
  88685. */
  88686. var BackgroundMaterial = /** @class */ (function (_super) {
  88687. __extends(BackgroundMaterial, _super);
  88688. /**
  88689. * Instantiates a Background Material in the given scene
  88690. * @param name The friendly name of the material
  88691. * @param scene The scene to add the material to
  88692. */
  88693. function BackgroundMaterial(name, scene) {
  88694. var _this = _super.call(this, name, scene) || this;
  88695. /**
  88696. * Key light Color (multiply against the R channel of the environement texture)
  88697. */
  88698. _this.primaryColor = BABYLON.Color3.White();
  88699. /**
  88700. * Key light Level (allowing HDR output of the background)
  88701. */
  88702. _this.primaryLevel = 1;
  88703. /**
  88704. * Secondary light Color (multiply against the G channel of the environement texture)
  88705. */
  88706. _this.secondaryColor = BABYLON.Color3.Gray();
  88707. /**
  88708. * Secondary light Level (allowing HDR output of the background)
  88709. */
  88710. _this.secondaryLevel = 1;
  88711. /**
  88712. * Tertiary light Color (multiply against the B channel of the environement texture)
  88713. */
  88714. _this.tertiaryColor = BABYLON.Color3.Black();
  88715. /**
  88716. * Tertiary light Level (allowing HDR output of the background)
  88717. */
  88718. _this.tertiaryLevel = 1;
  88719. /**
  88720. * Reflection Texture used in the material.
  88721. * Should be author in a specific way for the best result (refer to the documentation).
  88722. */
  88723. _this.reflectionTexture = null;
  88724. /**
  88725. * Reflection Texture level of blur.
  88726. *
  88727. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  88728. * texture twice.
  88729. */
  88730. _this.reflectionBlur = 0;
  88731. /**
  88732. * Diffuse Texture used in the material.
  88733. * Should be author in a specific way for the best result (refer to the documentation).
  88734. */
  88735. _this.diffuseTexture = null;
  88736. _this._shadowLights = null;
  88737. /**
  88738. * Specify the list of lights casting shadow on the material.
  88739. * All scene shadow lights will be included if null.
  88740. */
  88741. _this.shadowLights = null;
  88742. /**
  88743. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  88744. * soft lighting on the background.
  88745. */
  88746. _this.shadowBlurScale = 1;
  88747. /**
  88748. * Helps adjusting the shadow to a softer level if required.
  88749. * 0 means black shadows and 1 means no shadows.
  88750. */
  88751. _this.shadowLevel = 0;
  88752. /**
  88753. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  88754. * It is usually zero but might be interesting to modify according to your setup.
  88755. */
  88756. _this.sceneCenter = BABYLON.Vector3.Zero();
  88757. /**
  88758. * This helps specifying that the material is falling off to the sky box at grazing angle.
  88759. * This helps ensuring a nice transition when the camera goes under the ground.
  88760. */
  88761. _this.opacityFresnel = true;
  88762. /**
  88763. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  88764. * This helps adding a mirror texture on the ground.
  88765. */
  88766. _this.reflectionFresnel = false;
  88767. /**
  88768. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  88769. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  88770. */
  88771. _this.reflectionFalloffDistance = 0.0;
  88772. /**
  88773. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  88774. */
  88775. _this.reflectionAmount = 1.0;
  88776. /**
  88777. * This specifies the weight of the reflection at grazing angle.
  88778. */
  88779. _this.reflectionReflectance0 = 0.05;
  88780. /**
  88781. * This specifies the weight of the reflection at a perpendicular point of view.
  88782. */
  88783. _this.reflectionReflectance90 = 0.5;
  88784. /**
  88785. * Helps to directly use the maps channels instead of their level.
  88786. */
  88787. _this.useRGBColor = true;
  88788. /**
  88789. * This helps reducing the banding effect that could occur on the background.
  88790. */
  88791. _this.enableNoise = false;
  88792. _this._fovMultiplier = 1.0;
  88793. /**
  88794. * Enable the FOV adjustment feature controlled by fovMultiplier.
  88795. * @type {boolean}
  88796. */
  88797. _this.useEquirectangularFOV = false;
  88798. _this._maxSimultaneousLights = 4;
  88799. /**
  88800. * Number of Simultaneous lights allowed on the material.
  88801. */
  88802. _this.maxSimultaneousLights = 4;
  88803. /**
  88804. * Keep track of the image processing observer to allow dispose and replace.
  88805. */
  88806. _this._imageProcessingObserver = null;
  88807. /**
  88808. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  88809. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  88810. */
  88811. _this.switchToBGR = false;
  88812. // Temp values kept as cache in the material.
  88813. _this._renderTargets = new BABYLON.SmartArray(16);
  88814. _this._reflectionControls = BABYLON.Vector4.Zero();
  88815. // Setup the default processing configuration to the scene.
  88816. _this._attachImageProcessingConfiguration(null);
  88817. _this.getRenderTargetTextures = function () {
  88818. _this._renderTargets.reset();
  88819. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  88820. _this._renderTargets.push(_this._diffuseTexture);
  88821. }
  88822. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  88823. _this._renderTargets.push(_this._reflectionTexture);
  88824. }
  88825. return _this._renderTargets;
  88826. };
  88827. return _this;
  88828. }
  88829. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  88830. /**
  88831. * Sets the reflection reflectance fresnel values according to the default standard
  88832. * empirically know to work well :-)
  88833. */
  88834. set: function (value) {
  88835. var reflectionWeight = value;
  88836. if (reflectionWeight < 0.5) {
  88837. reflectionWeight = reflectionWeight * 2.0;
  88838. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  88839. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  88840. }
  88841. else {
  88842. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  88843. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  88844. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  88845. }
  88846. },
  88847. enumerable: true,
  88848. configurable: true
  88849. });
  88850. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  88851. /**
  88852. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  88853. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  88854. * Recommended to be keep at 1.0 except for special cases.
  88855. */
  88856. get: function () {
  88857. return this._fovMultiplier;
  88858. },
  88859. set: function (value) {
  88860. if (isNaN(value)) {
  88861. value = 1.0;
  88862. }
  88863. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  88864. },
  88865. enumerable: true,
  88866. configurable: true
  88867. });
  88868. /**
  88869. * Attaches a new image processing configuration to the PBR Material.
  88870. * @param configuration (if null the scene configuration will be use)
  88871. */
  88872. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  88873. var _this = this;
  88874. if (configuration === this._imageProcessingConfiguration) {
  88875. return;
  88876. }
  88877. // Detaches observer.
  88878. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88879. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88880. }
  88881. // Pick the scene configuration if needed.
  88882. if (!configuration) {
  88883. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  88884. }
  88885. else {
  88886. this._imageProcessingConfiguration = configuration;
  88887. }
  88888. // Attaches observer.
  88889. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  88890. _this._markAllSubMeshesAsImageProcessingDirty();
  88891. });
  88892. };
  88893. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  88894. /**
  88895. * Gets the image processing configuration used either in this material.
  88896. */
  88897. get: function () {
  88898. return this._imageProcessingConfiguration;
  88899. },
  88900. /**
  88901. * Sets the Default image processing configuration used either in the this material.
  88902. *
  88903. * If sets to null, the scene one is in use.
  88904. */
  88905. set: function (value) {
  88906. this._attachImageProcessingConfiguration(value);
  88907. // Ensure the effect will be rebuilt.
  88908. this._markAllSubMeshesAsTexturesDirty();
  88909. },
  88910. enumerable: true,
  88911. configurable: true
  88912. });
  88913. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  88914. /**
  88915. * Gets wether the color curves effect is enabled.
  88916. */
  88917. get: function () {
  88918. return this.imageProcessingConfiguration.colorCurvesEnabled;
  88919. },
  88920. /**
  88921. * Sets wether the color curves effect is enabled.
  88922. */
  88923. set: function (value) {
  88924. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  88925. },
  88926. enumerable: true,
  88927. configurable: true
  88928. });
  88929. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  88930. /**
  88931. * Gets wether the color grading effect is enabled.
  88932. */
  88933. get: function () {
  88934. return this.imageProcessingConfiguration.colorGradingEnabled;
  88935. },
  88936. /**
  88937. * Gets wether the color grading effect is enabled.
  88938. */
  88939. set: function (value) {
  88940. this.imageProcessingConfiguration.colorGradingEnabled = value;
  88941. },
  88942. enumerable: true,
  88943. configurable: true
  88944. });
  88945. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  88946. /**
  88947. * Gets wether tonemapping is enabled or not.
  88948. */
  88949. get: function () {
  88950. return this._imageProcessingConfiguration.toneMappingEnabled;
  88951. },
  88952. /**
  88953. * Sets wether tonemapping is enabled or not
  88954. */
  88955. set: function (value) {
  88956. this._imageProcessingConfiguration.toneMappingEnabled = value;
  88957. },
  88958. enumerable: true,
  88959. configurable: true
  88960. });
  88961. ;
  88962. ;
  88963. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  88964. /**
  88965. * The camera exposure used on this material.
  88966. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88967. * This corresponds to a photographic exposure.
  88968. */
  88969. get: function () {
  88970. return this._imageProcessingConfiguration.exposure;
  88971. },
  88972. /**
  88973. * The camera exposure used on this material.
  88974. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88975. * This corresponds to a photographic exposure.
  88976. */
  88977. set: function (value) {
  88978. this._imageProcessingConfiguration.exposure = value;
  88979. },
  88980. enumerable: true,
  88981. configurable: true
  88982. });
  88983. ;
  88984. ;
  88985. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  88986. /**
  88987. * Gets The camera contrast used on this material.
  88988. */
  88989. get: function () {
  88990. return this._imageProcessingConfiguration.contrast;
  88991. },
  88992. /**
  88993. * Sets The camera contrast used on this material.
  88994. */
  88995. set: function (value) {
  88996. this._imageProcessingConfiguration.contrast = value;
  88997. },
  88998. enumerable: true,
  88999. configurable: true
  89000. });
  89001. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  89002. /**
  89003. * Gets the Color Grading 2D Lookup Texture.
  89004. */
  89005. get: function () {
  89006. return this._imageProcessingConfiguration.colorGradingTexture;
  89007. },
  89008. /**
  89009. * Sets the Color Grading 2D Lookup Texture.
  89010. */
  89011. set: function (value) {
  89012. this.imageProcessingConfiguration.colorGradingTexture = value;
  89013. },
  89014. enumerable: true,
  89015. configurable: true
  89016. });
  89017. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  89018. /**
  89019. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89020. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89021. * 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;
  89022. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89023. */
  89024. get: function () {
  89025. return this.imageProcessingConfiguration.colorCurves;
  89026. },
  89027. /**
  89028. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89029. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89030. * 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;
  89031. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89032. */
  89033. set: function (value) {
  89034. this.imageProcessingConfiguration.colorCurves = value;
  89035. },
  89036. enumerable: true,
  89037. configurable: true
  89038. });
  89039. /**
  89040. * The entire material has been created in order to prevent overdraw.
  89041. * @returns false
  89042. */
  89043. BackgroundMaterial.prototype.needAlphaTesting = function () {
  89044. return true;
  89045. };
  89046. /**
  89047. * The entire material has been created in order to prevent overdraw.
  89048. * @returns true if blending is enable
  89049. */
  89050. BackgroundMaterial.prototype.needAlphaBlending = function () {
  89051. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  89052. };
  89053. /**
  89054. * Checks wether the material is ready to be rendered for a given mesh.
  89055. * @param mesh The mesh to render
  89056. * @param subMesh The submesh to check against
  89057. * @param useInstances Specify wether or not the material is used with instances
  89058. * @returns true if all the dependencies are ready (Textures, Effects...)
  89059. */
  89060. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  89061. var _this = this;
  89062. if (useInstances === void 0) { useInstances = false; }
  89063. if (subMesh.effect && this.isFrozen) {
  89064. if (this._wasPreviouslyReady) {
  89065. return true;
  89066. }
  89067. }
  89068. if (!subMesh._materialDefines) {
  89069. subMesh._materialDefines = new BackgroundMaterialDefines();
  89070. }
  89071. var scene = this.getScene();
  89072. var defines = subMesh._materialDefines;
  89073. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  89074. if (defines._renderId === scene.getRenderId()) {
  89075. return true;
  89076. }
  89077. }
  89078. var engine = scene.getEngine();
  89079. // Lights
  89080. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  89081. defines._needNormals = true;
  89082. // Textures
  89083. if (defines._areTexturesDirty) {
  89084. defines._needUVs = false;
  89085. if (scene.texturesEnabled) {
  89086. if (scene.getEngine().getCaps().textureLOD) {
  89087. defines.TEXTURELODSUPPORT = true;
  89088. }
  89089. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89090. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  89091. return false;
  89092. }
  89093. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  89094. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  89095. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  89096. defines.OPACITYFRESNEL = this._opacityFresnel;
  89097. }
  89098. else {
  89099. defines.DIFFUSE = false;
  89100. defines.DIFFUSEHASALPHA = false;
  89101. defines.GAMMADIFFUSE = false;
  89102. defines.OPACITYFRESNEL = false;
  89103. }
  89104. var reflectionTexture = this._reflectionTexture;
  89105. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89106. if (!reflectionTexture.isReadyOrNotBlocking()) {
  89107. return false;
  89108. }
  89109. defines.REFLECTION = true;
  89110. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  89111. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  89112. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  89113. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  89114. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  89115. defines.REFLECTIONBGR = this.switchToBGR;
  89116. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  89117. defines.INVERTCUBICMAP = true;
  89118. }
  89119. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  89120. switch (reflectionTexture.coordinatesMode) {
  89121. case BABYLON.Texture.CUBIC_MODE:
  89122. case BABYLON.Texture.INVCUBIC_MODE:
  89123. defines.REFLECTIONMAP_CUBIC = true;
  89124. break;
  89125. case BABYLON.Texture.EXPLICIT_MODE:
  89126. defines.REFLECTIONMAP_EXPLICIT = true;
  89127. break;
  89128. case BABYLON.Texture.PLANAR_MODE:
  89129. defines.REFLECTIONMAP_PLANAR = true;
  89130. break;
  89131. case BABYLON.Texture.PROJECTION_MODE:
  89132. defines.REFLECTIONMAP_PROJECTION = true;
  89133. break;
  89134. case BABYLON.Texture.SKYBOX_MODE:
  89135. defines.REFLECTIONMAP_SKYBOX = true;
  89136. break;
  89137. case BABYLON.Texture.SPHERICAL_MODE:
  89138. defines.REFLECTIONMAP_SPHERICAL = true;
  89139. break;
  89140. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  89141. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  89142. break;
  89143. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  89144. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  89145. break;
  89146. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  89147. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  89148. break;
  89149. }
  89150. if (this.reflectionFresnel) {
  89151. defines.REFLECTIONFRESNEL = true;
  89152. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  89153. this._reflectionControls.x = this.reflectionAmount;
  89154. this._reflectionControls.y = this.reflectionReflectance0;
  89155. this._reflectionControls.z = this.reflectionReflectance90;
  89156. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  89157. }
  89158. else {
  89159. defines.REFLECTIONFRESNEL = false;
  89160. defines.REFLECTIONFALLOFF = false;
  89161. }
  89162. }
  89163. else {
  89164. defines.REFLECTION = false;
  89165. defines.REFLECTIONFALLOFF = false;
  89166. defines.REFLECTIONBLUR = false;
  89167. defines.REFLECTIONMAP_3D = false;
  89168. defines.REFLECTIONMAP_SPHERICAL = false;
  89169. defines.REFLECTIONMAP_PLANAR = false;
  89170. defines.REFLECTIONMAP_CUBIC = false;
  89171. defines.REFLECTIONMAP_PROJECTION = false;
  89172. defines.REFLECTIONMAP_SKYBOX = false;
  89173. defines.REFLECTIONMAP_EXPLICIT = false;
  89174. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89175. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89176. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89177. defines.INVERTCUBICMAP = false;
  89178. defines.REFLECTIONMAP_OPPOSITEZ = false;
  89179. defines.LODINREFLECTIONALPHA = false;
  89180. defines.GAMMAREFLECTION = false;
  89181. }
  89182. }
  89183. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  89184. defines.USERGBCOLOR = this._useRGBColor;
  89185. defines.NOISE = this._enableNoise;
  89186. }
  89187. if (defines._areImageProcessingDirty) {
  89188. if (!this._imageProcessingConfiguration.isReady()) {
  89189. return false;
  89190. }
  89191. this._imageProcessingConfiguration.prepareDefines(defines);
  89192. }
  89193. // Misc.
  89194. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  89195. // Values that need to be evaluated on every frame
  89196. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  89197. // Attribs
  89198. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  89199. if (mesh) {
  89200. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  89201. mesh.createNormals(true);
  89202. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  89203. }
  89204. }
  89205. }
  89206. // Get correct effect
  89207. if (defines.isDirty) {
  89208. defines.markAsProcessed();
  89209. scene.resetCachedMaterial();
  89210. // Fallbacks
  89211. var fallbacks = new BABYLON.EffectFallbacks();
  89212. if (defines.FOG) {
  89213. fallbacks.addFallback(0, "FOG");
  89214. }
  89215. if (defines.POINTSIZE) {
  89216. fallbacks.addFallback(1, "POINTSIZE");
  89217. }
  89218. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  89219. if (defines.NUM_BONE_INFLUENCERS > 0) {
  89220. fallbacks.addCPUSkinningFallback(0, mesh);
  89221. }
  89222. //Attributes
  89223. var attribs = [BABYLON.VertexBuffer.PositionKind];
  89224. if (defines.NORMAL) {
  89225. attribs.push(BABYLON.VertexBuffer.NormalKind);
  89226. }
  89227. if (defines.UV1) {
  89228. attribs.push(BABYLON.VertexBuffer.UVKind);
  89229. }
  89230. if (defines.UV2) {
  89231. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89232. }
  89233. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  89234. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  89235. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  89236. "vFogInfos", "vFogColor", "pointSize",
  89237. "vClipPlane", "mBones",
  89238. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  89239. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  89240. "shadowLevel", "alpha",
  89241. "vBackgroundCenter", "vReflectionControl",
  89242. "vDiffuseInfos", "diffuseMatrix",
  89243. ];
  89244. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  89245. var uniformBuffers = ["Material", "Scene"];
  89246. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  89247. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  89248. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  89249. uniformsNames: uniforms,
  89250. uniformBuffersNames: uniformBuffers,
  89251. samplers: samplers,
  89252. defines: defines,
  89253. maxSimultaneousLights: this._maxSimultaneousLights
  89254. });
  89255. var onCompiled = function (effect) {
  89256. if (_this.onCompiled) {
  89257. _this.onCompiled(effect);
  89258. }
  89259. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  89260. };
  89261. var join = defines.toString();
  89262. subMesh.setEffect(scene.getEngine().createEffect("background", {
  89263. attributes: attribs,
  89264. uniformsNames: uniforms,
  89265. uniformBuffersNames: uniformBuffers,
  89266. samplers: samplers,
  89267. defines: join,
  89268. fallbacks: fallbacks,
  89269. onCompiled: onCompiled,
  89270. onError: this.onError,
  89271. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  89272. }, engine), defines);
  89273. this.buildUniformLayout();
  89274. }
  89275. if (!subMesh.effect || !subMesh.effect.isReady()) {
  89276. return false;
  89277. }
  89278. defines._renderId = scene.getRenderId();
  89279. this._wasPreviouslyReady = true;
  89280. return true;
  89281. };
  89282. /**
  89283. * Build the uniform buffer used in the material.
  89284. */
  89285. BackgroundMaterial.prototype.buildUniformLayout = function () {
  89286. // Order is important !
  89287. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  89288. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  89289. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  89290. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  89291. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  89292. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  89293. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  89294. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  89295. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  89296. this._uniformBuffer.addUniform("pointSize", 1);
  89297. this._uniformBuffer.addUniform("shadowLevel", 1);
  89298. this._uniformBuffer.addUniform("alpha", 1);
  89299. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  89300. this._uniformBuffer.addUniform("vReflectionControl", 4);
  89301. this._uniformBuffer.create();
  89302. };
  89303. /**
  89304. * Unbind the material.
  89305. */
  89306. BackgroundMaterial.prototype.unbind = function () {
  89307. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  89308. this._uniformBuffer.setTexture("diffuseSampler", null);
  89309. }
  89310. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  89311. this._uniformBuffer.setTexture("reflectionSampler", null);
  89312. }
  89313. _super.prototype.unbind.call(this);
  89314. };
  89315. /**
  89316. * Bind only the world matrix to the material.
  89317. * @param world The world matrix to bind.
  89318. */
  89319. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  89320. this._activeEffect.setMatrix("world", world);
  89321. };
  89322. /**
  89323. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  89324. * @param world The world matrix to bind.
  89325. * @param subMesh The submesh to bind for.
  89326. */
  89327. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  89328. var scene = this.getScene();
  89329. var defines = subMesh._materialDefines;
  89330. if (!defines) {
  89331. return;
  89332. }
  89333. var effect = subMesh.effect;
  89334. if (!effect) {
  89335. return;
  89336. }
  89337. this._activeEffect = effect;
  89338. // Matrices
  89339. this.bindOnlyWorldMatrix(world);
  89340. // Bones
  89341. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  89342. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  89343. if (mustRebind) {
  89344. this._uniformBuffer.bindToEffect(effect, "Material");
  89345. this.bindViewProjection(effect);
  89346. var reflectionTexture = this._reflectionTexture;
  89347. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  89348. // Texture uniforms
  89349. if (scene.texturesEnabled) {
  89350. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89351. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  89352. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  89353. }
  89354. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89355. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  89356. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  89357. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  89358. }
  89359. }
  89360. if (this.shadowLevel > 0) {
  89361. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  89362. }
  89363. this._uniformBuffer.updateFloat("alpha", this.alpha);
  89364. // Point size
  89365. if (this.pointsCloud) {
  89366. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  89367. }
  89368. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  89369. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  89370. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  89371. }
  89372. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  89373. // Textures
  89374. if (scene.texturesEnabled) {
  89375. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  89376. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  89377. }
  89378. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  89379. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  89380. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  89381. }
  89382. else if (!defines.REFLECTIONBLUR) {
  89383. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  89384. }
  89385. else {
  89386. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  89387. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  89388. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  89389. }
  89390. if (defines.REFLECTIONFRESNEL) {
  89391. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  89392. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  89393. }
  89394. }
  89395. }
  89396. // Clip plane
  89397. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  89398. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  89399. }
  89400. if (mustRebind || !this.isFrozen) {
  89401. if (scene.lightsEnabled) {
  89402. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  89403. }
  89404. // View
  89405. this.bindView(effect);
  89406. // Fog
  89407. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  89408. // image processing
  89409. this._imageProcessingConfiguration.bind(this._activeEffect);
  89410. }
  89411. this._uniformBuffer.update();
  89412. this._afterBind(mesh);
  89413. };
  89414. /**
  89415. * Dispose the material.
  89416. * @param forceDisposeEffect Force disposal of the associated effect.
  89417. * @param forceDisposeTextures Force disposal of the associated textures.
  89418. */
  89419. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  89420. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  89421. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  89422. if (forceDisposeTextures) {
  89423. if (this.diffuseTexture) {
  89424. this.diffuseTexture.dispose();
  89425. }
  89426. if (this.reflectionTexture) {
  89427. this.reflectionTexture.dispose();
  89428. }
  89429. }
  89430. this._renderTargets.dispose();
  89431. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89432. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89433. }
  89434. _super.prototype.dispose.call(this, forceDisposeEffect);
  89435. };
  89436. /**
  89437. * Clones the material.
  89438. * @param name The cloned name.
  89439. * @returns The cloned material.
  89440. */
  89441. BackgroundMaterial.prototype.clone = function (name) {
  89442. var _this = this;
  89443. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  89444. };
  89445. /**
  89446. * Serializes the current material to its JSON representation.
  89447. * @returns The JSON representation.
  89448. */
  89449. BackgroundMaterial.prototype.serialize = function () {
  89450. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89451. serializationObject.customType = "BABYLON.BackgroundMaterial";
  89452. return serializationObject;
  89453. };
  89454. /**
  89455. * Gets the class name of the material
  89456. * @returns "BackgroundMaterial"
  89457. */
  89458. BackgroundMaterial.prototype.getClassName = function () {
  89459. return "BackgroundMaterial";
  89460. };
  89461. /**
  89462. * Parse a JSON input to create back a background material.
  89463. * @param source The JSON data to parse
  89464. * @param scene The scene to create the parsed material in
  89465. * @param rootUrl The root url of the assets the material depends upon
  89466. * @returns the instantiated BackgroundMaterial.
  89467. */
  89468. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  89469. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  89470. };
  89471. /**
  89472. * Standard reflectance value at parallel view angle.
  89473. */
  89474. BackgroundMaterial.StandardReflectance0 = 0.05;
  89475. /**
  89476. * Standard reflectance value at grazing angle.
  89477. */
  89478. BackgroundMaterial.StandardReflectance90 = 0.5;
  89479. __decorate([
  89480. BABYLON.serializeAsColor3()
  89481. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  89482. __decorate([
  89483. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89484. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  89485. __decorate([
  89486. BABYLON.serialize()
  89487. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  89488. __decorate([
  89489. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89490. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  89491. __decorate([
  89492. BABYLON.serializeAsColor3()
  89493. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  89494. __decorate([
  89495. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89496. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  89497. __decorate([
  89498. BABYLON.serialize()
  89499. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  89500. __decorate([
  89501. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89502. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  89503. __decorate([
  89504. BABYLON.serializeAsColor3()
  89505. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  89506. __decorate([
  89507. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89508. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  89509. __decorate([
  89510. BABYLON.serialize()
  89511. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  89512. __decorate([
  89513. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  89514. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  89515. __decorate([
  89516. BABYLON.serializeAsTexture()
  89517. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  89518. __decorate([
  89519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89520. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  89521. __decorate([
  89522. BABYLON.serialize()
  89523. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  89524. __decorate([
  89525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89526. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  89527. __decorate([
  89528. BABYLON.serializeAsTexture()
  89529. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  89530. __decorate([
  89531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89532. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  89533. __decorate([
  89534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89535. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  89536. __decorate([
  89537. BABYLON.serialize()
  89538. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  89539. __decorate([
  89540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89541. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  89542. __decorate([
  89543. BABYLON.serialize()
  89544. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  89545. __decorate([
  89546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89547. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  89548. __decorate([
  89549. BABYLON.serializeAsVector3()
  89550. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  89551. __decorate([
  89552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89553. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  89554. __decorate([
  89555. BABYLON.serialize()
  89556. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  89557. __decorate([
  89558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89559. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  89560. __decorate([
  89561. BABYLON.serialize()
  89562. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  89563. __decorate([
  89564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89565. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  89566. __decorate([
  89567. BABYLON.serialize()
  89568. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  89569. __decorate([
  89570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89571. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  89572. __decorate([
  89573. BABYLON.serialize()
  89574. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  89575. __decorate([
  89576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89577. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  89578. __decorate([
  89579. BABYLON.serialize()
  89580. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  89581. __decorate([
  89582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89583. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  89584. __decorate([
  89585. BABYLON.serialize()
  89586. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  89587. __decorate([
  89588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89589. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  89590. __decorate([
  89591. BABYLON.serialize()
  89592. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  89593. __decorate([
  89594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89595. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  89596. __decorate([
  89597. BABYLON.serialize()
  89598. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  89599. __decorate([
  89600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89601. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  89602. __decorate([
  89603. BABYLON.serialize()
  89604. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  89605. __decorate([
  89606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89607. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  89608. __decorate([
  89609. BABYLON.serializeAsImageProcessingConfiguration()
  89610. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  89611. return BackgroundMaterial;
  89612. }(BABYLON.PushMaterial));
  89613. BABYLON.BackgroundMaterial = BackgroundMaterial;
  89614. })(BABYLON || (BABYLON = {}));
  89615. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  89616. var __assign = (this && this.__assign) || Object.assign || function(t) {
  89617. for (var s, i = 1, n = arguments.length; i < n; i++) {
  89618. s = arguments[i];
  89619. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  89620. t[p] = s[p];
  89621. }
  89622. return t;
  89623. };
  89624. var BABYLON;
  89625. (function (BABYLON) {
  89626. /**
  89627. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  89628. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  89629. * It also helps with the default setup of your imageProcessing configuration.
  89630. */
  89631. var EnvironmentHelper = /** @class */ (function () {
  89632. /**
  89633. * constructor
  89634. * @param options
  89635. * @param scene The scene to add the material to
  89636. */
  89637. function EnvironmentHelper(options, scene) {
  89638. var _this = this;
  89639. this._errorHandler = function (message, exception) {
  89640. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  89641. };
  89642. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  89643. this._scene = scene;
  89644. this.onErrorObservable = new BABYLON.Observable();
  89645. this._setupBackground();
  89646. this._setupImageProcessing();
  89647. }
  89648. /**
  89649. * Creates the default options for the helper.
  89650. */
  89651. EnvironmentHelper._getDefaultOptions = function () {
  89652. return {
  89653. createGround: true,
  89654. groundSize: 15,
  89655. groundTexture: this._groundTextureCDNUrl,
  89656. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89657. groundOpacity: 0.9,
  89658. enableGroundShadow: true,
  89659. groundShadowLevel: 0.5,
  89660. enableGroundMirror: false,
  89661. groundMirrorSizeRatio: 0.3,
  89662. groundMirrorBlurKernel: 64,
  89663. groundMirrorAmount: 1,
  89664. groundMirrorFresnelWeight: 1,
  89665. groundMirrorFallOffDistance: 0,
  89666. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  89667. groundYBias: 0.00001,
  89668. createSkybox: true,
  89669. skyboxSize: 20,
  89670. skyboxTexture: this._skyboxTextureCDNUrl,
  89671. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89672. backgroundYRotation: 0,
  89673. sizeAuto: true,
  89674. rootPosition: BABYLON.Vector3.Zero(),
  89675. setupImageProcessing: true,
  89676. environmentTexture: this._environmentTextureCDNUrl,
  89677. cameraExposure: 0.8,
  89678. cameraContrast: 1.2,
  89679. toneMappingEnabled: true,
  89680. };
  89681. };
  89682. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  89683. /**
  89684. * Gets the root mesh created by the helper.
  89685. */
  89686. get: function () {
  89687. return this._rootMesh;
  89688. },
  89689. enumerable: true,
  89690. configurable: true
  89691. });
  89692. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  89693. /**
  89694. * Gets the skybox created by the helper.
  89695. */
  89696. get: function () {
  89697. return this._skybox;
  89698. },
  89699. enumerable: true,
  89700. configurable: true
  89701. });
  89702. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  89703. /**
  89704. * Gets the skybox texture created by the helper.
  89705. */
  89706. get: function () {
  89707. return this._skyboxTexture;
  89708. },
  89709. enumerable: true,
  89710. configurable: true
  89711. });
  89712. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  89713. /**
  89714. * Gets the skybox material created by the helper.
  89715. */
  89716. get: function () {
  89717. return this._skyboxMaterial;
  89718. },
  89719. enumerable: true,
  89720. configurable: true
  89721. });
  89722. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  89723. /**
  89724. * Gets the ground mesh created by the helper.
  89725. */
  89726. get: function () {
  89727. return this._ground;
  89728. },
  89729. enumerable: true,
  89730. configurable: true
  89731. });
  89732. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  89733. /**
  89734. * Gets the ground texture created by the helper.
  89735. */
  89736. get: function () {
  89737. return this._groundTexture;
  89738. },
  89739. enumerable: true,
  89740. configurable: true
  89741. });
  89742. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  89743. /**
  89744. * Gets the ground mirror created by the helper.
  89745. */
  89746. get: function () {
  89747. return this._groundMirror;
  89748. },
  89749. enumerable: true,
  89750. configurable: true
  89751. });
  89752. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  89753. /**
  89754. * Gets the ground mirror render list to helps pushing the meshes
  89755. * you wish in the ground reflection.
  89756. */
  89757. get: function () {
  89758. if (this._groundMirror) {
  89759. return this._groundMirror.renderList;
  89760. }
  89761. return null;
  89762. },
  89763. enumerable: true,
  89764. configurable: true
  89765. });
  89766. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  89767. /**
  89768. * Gets the ground material created by the helper.
  89769. */
  89770. get: function () {
  89771. return this._groundMaterial;
  89772. },
  89773. enumerable: true,
  89774. configurable: true
  89775. });
  89776. /**
  89777. * Updates the background according to the new options
  89778. * @param options
  89779. */
  89780. EnvironmentHelper.prototype.updateOptions = function (options) {
  89781. var newOptions = __assign({}, this._options, options);
  89782. if (this._ground && !newOptions.createGround) {
  89783. this._ground.dispose();
  89784. this._ground = null;
  89785. }
  89786. if (this._groundMaterial && !newOptions.createGround) {
  89787. this._groundMaterial.dispose();
  89788. this._groundMaterial = null;
  89789. }
  89790. if (this._groundTexture) {
  89791. if (this._options.groundTexture != newOptions.groundTexture) {
  89792. this._groundTexture.dispose();
  89793. this._groundTexture = null;
  89794. }
  89795. }
  89796. if (this._skybox && !newOptions.createSkybox) {
  89797. this._skybox.dispose();
  89798. this._skybox = null;
  89799. }
  89800. if (this._skyboxMaterial && !newOptions.createSkybox) {
  89801. this._skyboxMaterial.dispose();
  89802. this._skyboxMaterial = null;
  89803. }
  89804. if (this._skyboxTexture) {
  89805. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  89806. this._skyboxTexture.dispose();
  89807. this._skyboxTexture = null;
  89808. }
  89809. }
  89810. if (this._groundMirror && !newOptions.enableGroundMirror) {
  89811. this._groundMirror.dispose();
  89812. this._groundMirror = null;
  89813. }
  89814. if (this._scene.environmentTexture) {
  89815. if (this._options.environmentTexture != newOptions.environmentTexture) {
  89816. this._scene.environmentTexture.dispose();
  89817. }
  89818. }
  89819. this._options = newOptions;
  89820. this._setupBackground();
  89821. this._setupImageProcessing();
  89822. };
  89823. /**
  89824. * Sets the primary color of all the available elements.
  89825. * @param color
  89826. */
  89827. EnvironmentHelper.prototype.setMainColor = function (color) {
  89828. if (this.groundMaterial) {
  89829. this.groundMaterial.primaryColor = color;
  89830. }
  89831. if (this.skyboxMaterial) {
  89832. this.skyboxMaterial.primaryColor = color;
  89833. }
  89834. if (this.groundMirror) {
  89835. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  89836. }
  89837. };
  89838. /**
  89839. * Setup the image processing according to the specified options.
  89840. */
  89841. EnvironmentHelper.prototype._setupImageProcessing = function () {
  89842. if (this._options.setupImageProcessing) {
  89843. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  89844. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  89845. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  89846. this._setupEnvironmentTexture();
  89847. }
  89848. };
  89849. /**
  89850. * Setup the environment texture according to the specified options.
  89851. */
  89852. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  89853. if (this._scene.environmentTexture) {
  89854. return;
  89855. }
  89856. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  89857. this._scene.environmentTexture = this._options.environmentTexture;
  89858. return;
  89859. }
  89860. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  89861. this._scene.environmentTexture = environmentTexture;
  89862. };
  89863. /**
  89864. * Setup the background according to the specified options.
  89865. */
  89866. EnvironmentHelper.prototype._setupBackground = function () {
  89867. if (!this._rootMesh) {
  89868. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  89869. }
  89870. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  89871. var sceneSize = this._getSceneSize();
  89872. if (this._options.createGround) {
  89873. this._setupGround(sceneSize);
  89874. this._setupGroundMaterial();
  89875. this._setupGroundDiffuseTexture();
  89876. if (this._options.enableGroundMirror) {
  89877. this._setupGroundMirrorTexture(sceneSize);
  89878. }
  89879. this._setupMirrorInGroundMaterial();
  89880. }
  89881. if (this._options.createSkybox) {
  89882. this._setupSkybox(sceneSize);
  89883. this._setupSkyboxMaterial();
  89884. this._setupSkyboxReflectionTexture();
  89885. }
  89886. this._rootMesh.position.x = sceneSize.rootPosition.x;
  89887. this._rootMesh.position.z = sceneSize.rootPosition.z;
  89888. this._rootMesh.position.y = sceneSize.rootPosition.y;
  89889. };
  89890. /**
  89891. * Get the scene sizes according to the setup.
  89892. */
  89893. EnvironmentHelper.prototype._getSceneSize = function () {
  89894. var _this = this;
  89895. var groundSize = this._options.groundSize;
  89896. var skyboxSize = this._options.skyboxSize;
  89897. var rootPosition = this._options.rootPosition;
  89898. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  89899. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89900. }
  89901. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  89902. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  89903. });
  89904. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  89905. if (this._options.sizeAuto) {
  89906. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  89907. this._scene.activeCamera.upperRadiusLimit) {
  89908. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  89909. skyboxSize = groundSize;
  89910. }
  89911. var sceneDiagonalLenght = sceneDiagonal.length();
  89912. if (sceneDiagonalLenght > groundSize) {
  89913. groundSize = sceneDiagonalLenght * 2;
  89914. skyboxSize = groundSize;
  89915. }
  89916. // 10 % bigger.
  89917. groundSize *= 1.1;
  89918. skyboxSize *= 1.5;
  89919. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  89920. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  89921. }
  89922. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89923. };
  89924. /**
  89925. * Setup the ground according to the specified options.
  89926. */
  89927. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  89928. var _this = this;
  89929. if (!this._ground) {
  89930. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  89931. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  89932. this._ground.parent = this._rootMesh;
  89933. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  89934. }
  89935. this._ground.receiveShadows = this._options.enableGroundShadow;
  89936. };
  89937. /**
  89938. * Setup the ground material according to the specified options.
  89939. */
  89940. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  89941. if (!this._groundMaterial) {
  89942. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  89943. }
  89944. this._groundMaterial.alpha = this._options.groundOpacity;
  89945. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  89946. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  89947. this._groundMaterial.primaryLevel = 1;
  89948. this._groundMaterial.primaryColor = this._options.groundColor;
  89949. this._groundMaterial.secondaryLevel = 0;
  89950. this._groundMaterial.tertiaryLevel = 0;
  89951. this._groundMaterial.useRGBColor = false;
  89952. this._groundMaterial.enableNoise = true;
  89953. if (this._ground) {
  89954. this._ground.material = this._groundMaterial;
  89955. }
  89956. };
  89957. /**
  89958. * Setup the ground diffuse texture according to the specified options.
  89959. */
  89960. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  89961. if (!this._groundMaterial) {
  89962. return;
  89963. }
  89964. if (this._groundTexture) {
  89965. return;
  89966. }
  89967. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  89968. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  89969. return;
  89970. }
  89971. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  89972. diffuseTexture.gammaSpace = false;
  89973. diffuseTexture.hasAlpha = true;
  89974. this._groundMaterial.diffuseTexture = diffuseTexture;
  89975. };
  89976. /**
  89977. * Setup the ground mirror texture according to the specified options.
  89978. */
  89979. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  89980. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89981. if (!this._groundMirror) {
  89982. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  89983. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  89984. this._groundMirror.anisotropicFilteringLevel = 1;
  89985. this._groundMirror.wrapU = wrapping;
  89986. this._groundMirror.wrapV = wrapping;
  89987. this._groundMirror.gammaSpace = false;
  89988. if (this._groundMirror.renderList) {
  89989. for (var i = 0; i < this._scene.meshes.length; i++) {
  89990. var mesh = this._scene.meshes[i];
  89991. if (mesh !== this._ground &&
  89992. mesh !== this._skybox &&
  89993. mesh !== this._rootMesh) {
  89994. this._groundMirror.renderList.push(mesh);
  89995. }
  89996. }
  89997. }
  89998. }
  89999. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  90000. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  90001. };
  90002. /**
  90003. * Setup the ground to receive the mirror texture.
  90004. */
  90005. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  90006. if (this._groundMaterial) {
  90007. this._groundMaterial.reflectionTexture = this._groundMirror;
  90008. this._groundMaterial.reflectionFresnel = true;
  90009. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  90010. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  90011. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  90012. }
  90013. };
  90014. /**
  90015. * Setup the skybox according to the specified options.
  90016. */
  90017. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  90018. var _this = this;
  90019. if (!this._skybox) {
  90020. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  90021. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  90022. }
  90023. this._skybox.parent = this._rootMesh;
  90024. };
  90025. /**
  90026. * Setup the skybox material according to the specified options.
  90027. */
  90028. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  90029. if (!this._skybox) {
  90030. return;
  90031. }
  90032. if (!this._skyboxMaterial) {
  90033. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  90034. }
  90035. this._skyboxMaterial.useRGBColor = false;
  90036. this._skyboxMaterial.primaryLevel = 1;
  90037. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  90038. this._skyboxMaterial.secondaryLevel = 0;
  90039. this._skyboxMaterial.tertiaryLevel = 0;
  90040. this._skyboxMaterial.enableNoise = true;
  90041. this._skybox.material = this._skyboxMaterial;
  90042. };
  90043. /**
  90044. * Setup the skybox reflection texture according to the specified options.
  90045. */
  90046. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  90047. if (!this._skyboxMaterial) {
  90048. return;
  90049. }
  90050. if (this._skyboxTexture) {
  90051. return;
  90052. }
  90053. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  90054. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90055. return;
  90056. }
  90057. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  90058. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  90059. this._skyboxTexture.gammaSpace = false;
  90060. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  90061. };
  90062. /**
  90063. * Dispose all the elements created by the Helper.
  90064. */
  90065. EnvironmentHelper.prototype.dispose = function () {
  90066. if (this._groundMaterial) {
  90067. this._groundMaterial.dispose(true, true);
  90068. }
  90069. if (this._skyboxMaterial) {
  90070. this._skyboxMaterial.dispose(true, true);
  90071. }
  90072. this._rootMesh.dispose(false);
  90073. };
  90074. /**
  90075. * Default ground texture URL.
  90076. */
  90077. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  90078. /**
  90079. * Default skybox texture URL.
  90080. */
  90081. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  90082. /**
  90083. * Default environment texture URL.
  90084. */
  90085. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  90086. return EnvironmentHelper;
  90087. }());
  90088. BABYLON.EnvironmentHelper = EnvironmentHelper;
  90089. })(BABYLON || (BABYLON = {}));
  90090. //# sourceMappingURL=babylon.environmentHelper.js.map
  90091. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\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#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\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=toLinearSpace(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 radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\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}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\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}","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","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","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\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\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#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\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#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  90092. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\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=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,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}","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};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\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};"};
  90093. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  90094. var BABYLON;
  90095. (function (BABYLON) {
  90096. var GridMaterialDefines = /** @class */ (function (_super) {
  90097. __extends(GridMaterialDefines, _super);
  90098. function GridMaterialDefines() {
  90099. var _this = _super.call(this) || this;
  90100. _this.TRANSPARENT = false;
  90101. _this.FOG = false;
  90102. _this.PREMULTIPLYALPHA = false;
  90103. _this.rebuild();
  90104. return _this;
  90105. }
  90106. return GridMaterialDefines;
  90107. }(BABYLON.MaterialDefines));
  90108. /**
  90109. * The grid materials allows you to wrap any shape with a grid.
  90110. * Colors are customizable.
  90111. */
  90112. var GridMaterial = /** @class */ (function (_super) {
  90113. __extends(GridMaterial, _super);
  90114. /**
  90115. * constructor
  90116. * @param name The name given to the material in order to identify it afterwards.
  90117. * @param scene The scene the material is used in.
  90118. */
  90119. function GridMaterial(name, scene) {
  90120. var _this = _super.call(this, name, scene) || this;
  90121. /**
  90122. * Main color of the grid (e.g. between lines)
  90123. */
  90124. _this.mainColor = BABYLON.Color3.Black();
  90125. /**
  90126. * Color of the grid lines.
  90127. */
  90128. _this.lineColor = BABYLON.Color3.Teal();
  90129. /**
  90130. * The scale of the grid compared to unit.
  90131. */
  90132. _this.gridRatio = 1.0;
  90133. /**
  90134. * Allows setting an offset for the grid lines.
  90135. */
  90136. _this.gridOffset = BABYLON.Vector3.Zero();
  90137. /**
  90138. * The frequency of thicker lines.
  90139. */
  90140. _this.majorUnitFrequency = 10;
  90141. /**
  90142. * The visibility of minor units in the grid.
  90143. */
  90144. _this.minorUnitVisibility = 0.33;
  90145. /**
  90146. * The grid opacity outside of the lines.
  90147. */
  90148. _this.opacity = 1.0;
  90149. /**
  90150. * Determine RBG output is premultiplied by alpha value.
  90151. */
  90152. _this.preMultiplyAlpha = false;
  90153. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  90154. return _this;
  90155. }
  90156. /**
  90157. * Returns wehter or not the grid requires alpha blending.
  90158. */
  90159. GridMaterial.prototype.needAlphaBlending = function () {
  90160. return this.opacity < 1.0;
  90161. };
  90162. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  90163. return this.needAlphaBlending();
  90164. };
  90165. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  90166. if (this.isFrozen) {
  90167. if (this._wasPreviouslyReady && subMesh.effect) {
  90168. return true;
  90169. }
  90170. }
  90171. if (!subMesh._materialDefines) {
  90172. subMesh._materialDefines = new GridMaterialDefines();
  90173. }
  90174. var defines = subMesh._materialDefines;
  90175. var scene = this.getScene();
  90176. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  90177. if (this._renderId === scene.getRenderId()) {
  90178. return true;
  90179. }
  90180. }
  90181. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  90182. defines.TRANSPARENT = !defines.TRANSPARENT;
  90183. defines.markAsUnprocessed();
  90184. }
  90185. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  90186. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  90187. defines.markAsUnprocessed();
  90188. }
  90189. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  90190. // Get correct effect
  90191. if (defines.isDirty) {
  90192. defines.markAsProcessed();
  90193. scene.resetCachedMaterial();
  90194. // Attributes
  90195. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90196. // Defines
  90197. var join = defines.toString();
  90198. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  90199. }
  90200. if (!subMesh.effect || !subMesh.effect.isReady()) {
  90201. return false;
  90202. }
  90203. this._renderId = scene.getRenderId();
  90204. this._wasPreviouslyReady = true;
  90205. return true;
  90206. };
  90207. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  90208. var scene = this.getScene();
  90209. var defines = subMesh._materialDefines;
  90210. if (!defines) {
  90211. return;
  90212. }
  90213. var effect = subMesh.effect;
  90214. if (!effect) {
  90215. return;
  90216. }
  90217. this._activeEffect = effect;
  90218. // Matrices
  90219. this.bindOnlyWorldMatrix(world);
  90220. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  90221. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  90222. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  90223. // Uniforms
  90224. if (this._mustRebind(scene, effect)) {
  90225. this._activeEffect.setColor3("mainColor", this.mainColor);
  90226. this._activeEffect.setColor3("lineColor", this.lineColor);
  90227. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  90228. this._gridControl.x = this.gridRatio;
  90229. this._gridControl.y = Math.round(this.majorUnitFrequency);
  90230. this._gridControl.z = this.minorUnitVisibility;
  90231. this._gridControl.w = this.opacity;
  90232. this._activeEffect.setVector4("gridControl", this._gridControl);
  90233. }
  90234. // Fog
  90235. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  90236. this._afterBind(mesh, this._activeEffect);
  90237. };
  90238. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  90239. _super.prototype.dispose.call(this, forceDisposeEffect);
  90240. };
  90241. GridMaterial.prototype.clone = function (name) {
  90242. var _this = this;
  90243. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  90244. };
  90245. GridMaterial.prototype.serialize = function () {
  90246. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90247. serializationObject.customType = "BABYLON.GridMaterial";
  90248. return serializationObject;
  90249. };
  90250. GridMaterial.prototype.getClassName = function () {
  90251. return "GridMaterial";
  90252. };
  90253. GridMaterial.Parse = function (source, scene, rootUrl) {
  90254. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  90255. };
  90256. __decorate([
  90257. BABYLON.serializeAsColor3()
  90258. ], GridMaterial.prototype, "mainColor", void 0);
  90259. __decorate([
  90260. BABYLON.serializeAsColor3()
  90261. ], GridMaterial.prototype, "lineColor", void 0);
  90262. __decorate([
  90263. BABYLON.serialize()
  90264. ], GridMaterial.prototype, "gridRatio", void 0);
  90265. __decorate([
  90266. BABYLON.serializeAsColor3()
  90267. ], GridMaterial.prototype, "gridOffset", void 0);
  90268. __decorate([
  90269. BABYLON.serialize()
  90270. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  90271. __decorate([
  90272. BABYLON.serialize()
  90273. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  90274. __decorate([
  90275. BABYLON.serialize()
  90276. ], GridMaterial.prototype, "opacity", void 0);
  90277. __decorate([
  90278. BABYLON.serialize()
  90279. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  90280. return GridMaterial;
  90281. }(BABYLON.PushMaterial));
  90282. BABYLON.GridMaterial = GridMaterial;
  90283. })(BABYLON || (BABYLON = {}));
  90284. //# sourceMappingURL=babylon.gridmaterial.js.map
  90285. 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}";
  90286. 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}";
  90287. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  90288. var BABYLON;
  90289. (function (BABYLON) {
  90290. var GLTFLoaderCoordinateSystemMode;
  90291. (function (GLTFLoaderCoordinateSystemMode) {
  90292. /**
  90293. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  90294. */
  90295. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  90296. /**
  90297. * Sets the useRightHandedSystem flag on the scene.
  90298. */
  90299. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  90300. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  90301. var GLTFLoaderAnimationStartMode;
  90302. (function (GLTFLoaderAnimationStartMode) {
  90303. /**
  90304. * No animation will start.
  90305. */
  90306. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  90307. /**
  90308. * The first animation will start.
  90309. */
  90310. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  90311. /**
  90312. * All animations will start.
  90313. */
  90314. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  90315. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  90316. var GLTFLoaderState;
  90317. (function (GLTFLoaderState) {
  90318. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  90319. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  90320. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  90321. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  90322. var GLTFFileLoader = /** @class */ (function () {
  90323. function GLTFFileLoader() {
  90324. // #region Common options
  90325. /**
  90326. * Raised when the asset has been parsed.
  90327. * The data.json property stores the glTF JSON.
  90328. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  90329. */
  90330. this.onParsedObservable = new BABYLON.Observable();
  90331. // #endregion
  90332. // #region V2 options
  90333. /**
  90334. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  90335. */
  90336. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  90337. /**
  90338. * The animation start mode (NONE, FIRST, ALL).
  90339. */
  90340. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  90341. /**
  90342. * Set to true to compile materials before raising the success callback.
  90343. */
  90344. this.compileMaterials = false;
  90345. /**
  90346. * Set to true to also compile materials with clip planes.
  90347. */
  90348. this.useClipPlane = false;
  90349. /**
  90350. * Set to true to compile shadow generators before raising the success callback.
  90351. */
  90352. this.compileShadowGenerators = false;
  90353. /**
  90354. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  90355. */
  90356. this.onMeshLoadedObservable = new BABYLON.Observable();
  90357. /**
  90358. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  90359. */
  90360. this.onTextureLoadedObservable = new BABYLON.Observable();
  90361. /**
  90362. * Raised when the loader creates a material after parsing the glTF properties of the material.
  90363. */
  90364. this.onMaterialLoadedObservable = new BABYLON.Observable();
  90365. /**
  90366. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  90367. */
  90368. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  90369. /**
  90370. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  90371. * For assets with LODs, raised when all of the LODs are complete.
  90372. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  90373. */
  90374. this.onCompleteObservable = new BABYLON.Observable();
  90375. /**
  90376. * Raised when the loader is disposed.
  90377. */
  90378. this.onDisposeObservable = new BABYLON.Observable();
  90379. /**
  90380. * Raised after a loader extension is created.
  90381. * Set additional options for a loader extension in this event.
  90382. */
  90383. this.onExtensionLoadedObservable = new BABYLON.Observable();
  90384. // #endregion
  90385. this._loader = null;
  90386. this.name = "gltf";
  90387. this.extensions = {
  90388. ".gltf": { isBinary: false },
  90389. ".glb": { isBinary: true }
  90390. };
  90391. }
  90392. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  90393. set: function (callback) {
  90394. if (this._onParsedObserver) {
  90395. this.onParsedObservable.remove(this._onParsedObserver);
  90396. }
  90397. this._onParsedObserver = this.onParsedObservable.add(callback);
  90398. },
  90399. enumerable: true,
  90400. configurable: true
  90401. });
  90402. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  90403. set: function (callback) {
  90404. if (this._onMeshLoadedObserver) {
  90405. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  90406. }
  90407. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  90408. },
  90409. enumerable: true,
  90410. configurable: true
  90411. });
  90412. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  90413. set: function (callback) {
  90414. if (this._onTextureLoadedObserver) {
  90415. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  90416. }
  90417. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  90418. },
  90419. enumerable: true,
  90420. configurable: true
  90421. });
  90422. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  90423. set: function (callback) {
  90424. if (this._onMaterialLoadedObserver) {
  90425. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  90426. }
  90427. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  90428. },
  90429. enumerable: true,
  90430. configurable: true
  90431. });
  90432. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  90433. set: function (callback) {
  90434. if (this._onAnimationGroupLoadedObserver) {
  90435. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  90436. }
  90437. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  90438. },
  90439. enumerable: true,
  90440. configurable: true
  90441. });
  90442. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  90443. set: function (callback) {
  90444. if (this._onCompleteObserver) {
  90445. this.onCompleteObservable.remove(this._onCompleteObserver);
  90446. }
  90447. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  90448. },
  90449. enumerable: true,
  90450. configurable: true
  90451. });
  90452. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  90453. set: function (callback) {
  90454. if (this._onDisposeObserver) {
  90455. this.onDisposeObservable.remove(this._onDisposeObserver);
  90456. }
  90457. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  90458. },
  90459. enumerable: true,
  90460. configurable: true
  90461. });
  90462. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  90463. set: function (callback) {
  90464. if (this._onExtensionLoadedObserver) {
  90465. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  90466. }
  90467. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  90468. },
  90469. enumerable: true,
  90470. configurable: true
  90471. });
  90472. /**
  90473. * Gets a promise that resolves when the asset is completely loaded.
  90474. * @returns A promise that resolves when the asset is completely loaded.
  90475. */
  90476. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  90477. var _this = this;
  90478. return new Promise(function (resolve) {
  90479. _this.onCompleteObservable.add(function () {
  90480. resolve();
  90481. }, undefined, undefined, undefined, true);
  90482. });
  90483. };
  90484. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  90485. /**
  90486. * The loader state or null if not active.
  90487. */
  90488. get: function () {
  90489. return this._loader ? this._loader.state : null;
  90490. },
  90491. enumerable: true,
  90492. configurable: true
  90493. });
  90494. /**
  90495. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  90496. */
  90497. GLTFFileLoader.prototype.dispose = function () {
  90498. if (this._loader) {
  90499. this._loader.dispose();
  90500. this._loader = null;
  90501. }
  90502. this.onMeshLoadedObservable.clear();
  90503. this.onTextureLoadedObservable.clear();
  90504. this.onMaterialLoadedObservable.clear();
  90505. this.onDisposeObservable.notifyObservers(this);
  90506. this.onDisposeObservable.clear();
  90507. };
  90508. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  90509. var _this = this;
  90510. return Promise.resolve().then(function () {
  90511. var loaderData = _this._parse(data);
  90512. _this._loader = _this._getLoader(loaderData);
  90513. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  90514. });
  90515. };
  90516. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  90517. var _this = this;
  90518. return Promise.resolve().then(function () {
  90519. var loaderData = _this._parse(data);
  90520. _this._loader = _this._getLoader(loaderData);
  90521. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  90522. });
  90523. };
  90524. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  90525. var _this = this;
  90526. return Promise.resolve().then(function () {
  90527. var loaderData = _this._parse(data);
  90528. _this._loader = _this._getLoader(loaderData);
  90529. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  90530. var container = new BABYLON.AssetContainer(scene);
  90531. Array.prototype.push.apply(container.meshes, result.meshes);
  90532. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  90533. Array.prototype.push.apply(container.skeletons, result.skeletons);
  90534. container.removeAllFromScene();
  90535. return container;
  90536. });
  90537. });
  90538. };
  90539. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  90540. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  90541. };
  90542. GLTFFileLoader.prototype.createPlugin = function () {
  90543. return new GLTFFileLoader();
  90544. };
  90545. GLTFFileLoader.prototype._parse = function (data) {
  90546. var parsedData;
  90547. if (data instanceof ArrayBuffer) {
  90548. parsedData = GLTFFileLoader._parseBinary(data);
  90549. }
  90550. else {
  90551. parsedData = {
  90552. json: JSON.parse(data),
  90553. bin: null
  90554. };
  90555. }
  90556. this.onParsedObservable.notifyObservers(parsedData);
  90557. this.onParsedObservable.clear();
  90558. return parsedData;
  90559. };
  90560. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  90561. var _this = this;
  90562. var loaderVersion = { major: 2, minor: 0 };
  90563. var asset = loaderData.json.asset || {};
  90564. var version = GLTFFileLoader._parseVersion(asset.version);
  90565. if (!version) {
  90566. throw new Error("Invalid version: " + asset.version);
  90567. }
  90568. if (asset.minVersion !== undefined) {
  90569. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  90570. if (!minVersion) {
  90571. throw new Error("Invalid minimum version: " + asset.minVersion);
  90572. }
  90573. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  90574. throw new Error("Incompatible minimum version: " + asset.minVersion);
  90575. }
  90576. }
  90577. var createLoaders = {
  90578. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  90579. 2: GLTFFileLoader.CreateGLTFLoaderV2
  90580. };
  90581. var createLoader = createLoaders[version.major];
  90582. if (!createLoader) {
  90583. throw new Error("Unsupported version: " + asset.version);
  90584. }
  90585. var loader = createLoader();
  90586. loader.coordinateSystemMode = this.coordinateSystemMode;
  90587. loader.animationStartMode = this.animationStartMode;
  90588. loader.compileMaterials = this.compileMaterials;
  90589. loader.useClipPlane = this.useClipPlane;
  90590. loader.compileShadowGenerators = this.compileShadowGenerators;
  90591. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  90592. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  90593. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  90594. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  90595. loader.onCompleteObservable.add(function () {
  90596. _this.onMeshLoadedObservable.clear();
  90597. _this.onTextureLoadedObservable.clear();
  90598. _this.onMaterialLoadedObservable.clear();
  90599. _this.onCompleteObservable.notifyObservers(_this);
  90600. _this.onCompleteObservable.clear();
  90601. });
  90602. return loader;
  90603. };
  90604. GLTFFileLoader._parseBinary = function (data) {
  90605. var Binary = {
  90606. Magic: 0x46546C67
  90607. };
  90608. var binaryReader = new BinaryReader(data);
  90609. var magic = binaryReader.readUint32();
  90610. if (magic !== Binary.Magic) {
  90611. throw new Error("Unexpected magic: " + magic);
  90612. }
  90613. var version = binaryReader.readUint32();
  90614. switch (version) {
  90615. case 1: return GLTFFileLoader._parseV1(binaryReader);
  90616. case 2: return GLTFFileLoader._parseV2(binaryReader);
  90617. }
  90618. throw new Error("Unsupported version: " + version);
  90619. };
  90620. GLTFFileLoader._parseV1 = function (binaryReader) {
  90621. var ContentFormat = {
  90622. JSON: 0
  90623. };
  90624. var length = binaryReader.readUint32();
  90625. if (length != binaryReader.getLength()) {
  90626. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  90627. }
  90628. var contentLength = binaryReader.readUint32();
  90629. var contentFormat = binaryReader.readUint32();
  90630. var content;
  90631. switch (contentFormat) {
  90632. case ContentFormat.JSON: {
  90633. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  90634. break;
  90635. }
  90636. default: {
  90637. throw new Error("Unexpected content format: " + contentFormat);
  90638. }
  90639. }
  90640. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  90641. var body = binaryReader.readUint8Array(bytesRemaining);
  90642. return {
  90643. json: content,
  90644. bin: body
  90645. };
  90646. };
  90647. GLTFFileLoader._parseV2 = function (binaryReader) {
  90648. var ChunkFormat = {
  90649. JSON: 0x4E4F534A,
  90650. BIN: 0x004E4942
  90651. };
  90652. var length = binaryReader.readUint32();
  90653. if (length !== binaryReader.getLength()) {
  90654. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  90655. }
  90656. // JSON chunk
  90657. var chunkLength = binaryReader.readUint32();
  90658. var chunkFormat = binaryReader.readUint32();
  90659. if (chunkFormat !== ChunkFormat.JSON) {
  90660. throw new Error("First chunk format is not JSON");
  90661. }
  90662. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  90663. // Look for BIN chunk
  90664. var bin = null;
  90665. while (binaryReader.getPosition() < binaryReader.getLength()) {
  90666. var chunkLength_1 = binaryReader.readUint32();
  90667. var chunkFormat_1 = binaryReader.readUint32();
  90668. switch (chunkFormat_1) {
  90669. case ChunkFormat.JSON: {
  90670. throw new Error("Unexpected JSON chunk");
  90671. }
  90672. case ChunkFormat.BIN: {
  90673. bin = binaryReader.readUint8Array(chunkLength_1);
  90674. break;
  90675. }
  90676. default: {
  90677. // ignore unrecognized chunkFormat
  90678. binaryReader.skipBytes(chunkLength_1);
  90679. break;
  90680. }
  90681. }
  90682. }
  90683. return {
  90684. json: json,
  90685. bin: bin
  90686. };
  90687. };
  90688. GLTFFileLoader._parseVersion = function (version) {
  90689. if (version === "1.0" || version === "1.0.1") {
  90690. return {
  90691. major: 1,
  90692. minor: 0
  90693. };
  90694. }
  90695. var match = (version + "").match(/^(\d+)\.(\d+)/);
  90696. if (!match) {
  90697. return null;
  90698. }
  90699. return {
  90700. major: parseInt(match[1]),
  90701. minor: parseInt(match[2])
  90702. };
  90703. };
  90704. GLTFFileLoader._compareVersion = function (a, b) {
  90705. if (a.major > b.major)
  90706. return 1;
  90707. if (a.major < b.major)
  90708. return -1;
  90709. if (a.minor > b.minor)
  90710. return 1;
  90711. if (a.minor < b.minor)
  90712. return -1;
  90713. return 0;
  90714. };
  90715. GLTFFileLoader._decodeBufferToText = function (buffer) {
  90716. var result = "";
  90717. var length = buffer.byteLength;
  90718. for (var i = 0; i < length; i++) {
  90719. result += String.fromCharCode(buffer[i]);
  90720. }
  90721. return result;
  90722. };
  90723. // #endregion
  90724. // #region V1 options
  90725. GLTFFileLoader.IncrementalLoading = true;
  90726. GLTFFileLoader.HomogeneousCoordinates = false;
  90727. return GLTFFileLoader;
  90728. }());
  90729. BABYLON.GLTFFileLoader = GLTFFileLoader;
  90730. var BinaryReader = /** @class */ (function () {
  90731. function BinaryReader(arrayBuffer) {
  90732. this._arrayBuffer = arrayBuffer;
  90733. this._dataView = new DataView(arrayBuffer);
  90734. this._byteOffset = 0;
  90735. }
  90736. BinaryReader.prototype.getPosition = function () {
  90737. return this._byteOffset;
  90738. };
  90739. BinaryReader.prototype.getLength = function () {
  90740. return this._arrayBuffer.byteLength;
  90741. };
  90742. BinaryReader.prototype.readUint32 = function () {
  90743. var value = this._dataView.getUint32(this._byteOffset, true);
  90744. this._byteOffset += 4;
  90745. return value;
  90746. };
  90747. BinaryReader.prototype.readUint8Array = function (length) {
  90748. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  90749. this._byteOffset += length;
  90750. return value;
  90751. };
  90752. BinaryReader.prototype.skipBytes = function (length) {
  90753. this._byteOffset += length;
  90754. };
  90755. return BinaryReader;
  90756. }());
  90757. if (BABYLON.SceneLoader) {
  90758. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  90759. }
  90760. })(BABYLON || (BABYLON = {}));
  90761. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  90762. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90763. var BABYLON;
  90764. (function (BABYLON) {
  90765. var GLTF1;
  90766. (function (GLTF1) {
  90767. /**
  90768. * Enums
  90769. */
  90770. var EComponentType;
  90771. (function (EComponentType) {
  90772. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  90773. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  90774. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  90775. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  90776. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  90777. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  90778. var EShaderType;
  90779. (function (EShaderType) {
  90780. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  90781. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  90782. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  90783. var EParameterType;
  90784. (function (EParameterType) {
  90785. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  90786. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  90787. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  90788. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  90789. EParameterType[EParameterType["INT"] = 5124] = "INT";
  90790. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  90791. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  90792. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  90793. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  90794. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  90795. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  90796. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  90797. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  90798. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  90799. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  90800. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  90801. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  90802. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  90803. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  90804. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  90805. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  90806. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  90807. var ETextureWrapMode;
  90808. (function (ETextureWrapMode) {
  90809. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  90810. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  90811. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  90812. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  90813. var ETextureFilterType;
  90814. (function (ETextureFilterType) {
  90815. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  90816. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  90817. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  90818. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  90819. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  90820. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  90821. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  90822. var ETextureFormat;
  90823. (function (ETextureFormat) {
  90824. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  90825. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  90826. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  90827. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  90828. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  90829. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  90830. var ECullingType;
  90831. (function (ECullingType) {
  90832. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  90833. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  90834. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  90835. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  90836. var EBlendingFunction;
  90837. (function (EBlendingFunction) {
  90838. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  90839. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  90840. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  90841. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  90842. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  90843. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  90844. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  90845. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  90846. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  90847. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  90848. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  90849. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  90850. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  90851. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  90852. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  90853. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  90854. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90855. })(BABYLON || (BABYLON = {}));
  90856. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  90857. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90858. var BABYLON;
  90859. (function (BABYLON) {
  90860. var GLTF1;
  90861. (function (GLTF1) {
  90862. /**
  90863. * Tokenizer. Used for shaders compatibility
  90864. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  90865. */
  90866. var ETokenType;
  90867. (function (ETokenType) {
  90868. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  90869. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  90870. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  90871. })(ETokenType || (ETokenType = {}));
  90872. var Tokenizer = /** @class */ (function () {
  90873. function Tokenizer(toParse) {
  90874. this._pos = 0;
  90875. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  90876. this._toParse = toParse;
  90877. this._maxPos = toParse.length;
  90878. }
  90879. Tokenizer.prototype.getNextToken = function () {
  90880. if (this.isEnd())
  90881. return ETokenType.END_OF_INPUT;
  90882. this.currentString = this.read();
  90883. this.currentToken = ETokenType.UNKNOWN;
  90884. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  90885. this.currentToken = ETokenType.IDENTIFIER;
  90886. this.currentIdentifier = this.currentString;
  90887. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  90888. this.currentIdentifier += this.currentString;
  90889. this.forward();
  90890. }
  90891. }
  90892. return this.currentToken;
  90893. };
  90894. Tokenizer.prototype.peek = function () {
  90895. return this._toParse[this._pos];
  90896. };
  90897. Tokenizer.prototype.read = function () {
  90898. return this._toParse[this._pos++];
  90899. };
  90900. Tokenizer.prototype.forward = function () {
  90901. this._pos++;
  90902. };
  90903. Tokenizer.prototype.isEnd = function () {
  90904. return this._pos >= this._maxPos;
  90905. };
  90906. return Tokenizer;
  90907. }());
  90908. /**
  90909. * Values
  90910. */
  90911. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  90912. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  90913. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  90914. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  90915. /**
  90916. * Parse
  90917. */
  90918. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  90919. for (var buf in parsedBuffers) {
  90920. var parsedBuffer = parsedBuffers[buf];
  90921. gltfRuntime.buffers[buf] = parsedBuffer;
  90922. gltfRuntime.buffersCount++;
  90923. }
  90924. };
  90925. var parseShaders = function (parsedShaders, gltfRuntime) {
  90926. for (var sha in parsedShaders) {
  90927. var parsedShader = parsedShaders[sha];
  90928. gltfRuntime.shaders[sha] = parsedShader;
  90929. gltfRuntime.shaderscount++;
  90930. }
  90931. };
  90932. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  90933. for (var object in parsedObjects) {
  90934. var parsedObject = parsedObjects[object];
  90935. gltfRuntime[runtimeProperty][object] = parsedObject;
  90936. }
  90937. };
  90938. /**
  90939. * Utils
  90940. */
  90941. var normalizeUVs = function (buffer) {
  90942. if (!buffer) {
  90943. return;
  90944. }
  90945. for (var i = 0; i < buffer.length / 2; i++) {
  90946. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  90947. }
  90948. };
  90949. var getAttribute = function (attributeParameter) {
  90950. if (attributeParameter.semantic === "NORMAL") {
  90951. return "normal";
  90952. }
  90953. else if (attributeParameter.semantic === "POSITION") {
  90954. return "position";
  90955. }
  90956. else if (attributeParameter.semantic === "JOINT") {
  90957. return "matricesIndices";
  90958. }
  90959. else if (attributeParameter.semantic === "WEIGHT") {
  90960. return "matricesWeights";
  90961. }
  90962. else if (attributeParameter.semantic === "COLOR") {
  90963. return "color";
  90964. }
  90965. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  90966. var channel = Number(attributeParameter.semantic.split("_")[1]);
  90967. return "uv" + (channel === 0 ? "" : channel + 1);
  90968. }
  90969. return null;
  90970. };
  90971. /**
  90972. * Loads and creates animations
  90973. */
  90974. var loadAnimations = function (gltfRuntime) {
  90975. for (var anim in gltfRuntime.animations) {
  90976. var animation = gltfRuntime.animations[anim];
  90977. if (!animation.channels || !animation.samplers) {
  90978. continue;
  90979. }
  90980. var lastAnimation = null;
  90981. for (var i = 0; i < animation.channels.length; i++) {
  90982. // Get parameters and load buffers
  90983. var channel = animation.channels[i];
  90984. var sampler = animation.samplers[channel.sampler];
  90985. if (!sampler) {
  90986. continue;
  90987. }
  90988. var inputData = null;
  90989. var outputData = null;
  90990. if (animation.parameters) {
  90991. inputData = animation.parameters[sampler.input];
  90992. outputData = animation.parameters[sampler.output];
  90993. }
  90994. else {
  90995. inputData = sampler.input;
  90996. outputData = sampler.output;
  90997. }
  90998. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  90999. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  91000. var targetID = channel.target.id;
  91001. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  91002. if (targetNode === null) {
  91003. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  91004. }
  91005. if (targetNode === null) {
  91006. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  91007. continue;
  91008. }
  91009. var isBone = targetNode instanceof BABYLON.Bone;
  91010. // Get target path (position, rotation or scaling)
  91011. var targetPath = channel.target.path;
  91012. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  91013. if (targetPathIndex !== -1) {
  91014. targetPath = babylonAnimationPaths[targetPathIndex];
  91015. }
  91016. // Determine animation type
  91017. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  91018. if (!isBone) {
  91019. if (targetPath === "rotationQuaternion") {
  91020. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  91021. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  91022. }
  91023. else {
  91024. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91025. }
  91026. }
  91027. // Create animation and key frames
  91028. var babylonAnimation = null;
  91029. var keys = [];
  91030. var arrayOffset = 0;
  91031. var modifyKey = false;
  91032. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  91033. babylonAnimation = lastAnimation;
  91034. modifyKey = true;
  91035. }
  91036. if (!modifyKey) {
  91037. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  91038. }
  91039. // For each frame
  91040. for (var j = 0; j < bufferInput.length; j++) {
  91041. var value = null;
  91042. if (targetPath === "rotationQuaternion") {
  91043. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  91044. arrayOffset += 4;
  91045. }
  91046. else {
  91047. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  91048. arrayOffset += 3;
  91049. }
  91050. if (isBone) {
  91051. var bone = targetNode;
  91052. var translation = BABYLON.Vector3.Zero();
  91053. var rotationQuaternion = new BABYLON.Quaternion();
  91054. var scaling = BABYLON.Vector3.Zero();
  91055. // Warning on decompose
  91056. var mat = bone.getBaseMatrix();
  91057. if (modifyKey && lastAnimation) {
  91058. mat = lastAnimation.getKeys()[j].value;
  91059. }
  91060. mat.decompose(scaling, rotationQuaternion, translation);
  91061. if (targetPath === "position") {
  91062. translation = value;
  91063. }
  91064. else if (targetPath === "rotationQuaternion") {
  91065. rotationQuaternion = value;
  91066. }
  91067. else {
  91068. scaling = value;
  91069. }
  91070. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  91071. }
  91072. if (!modifyKey) {
  91073. keys.push({
  91074. frame: bufferInput[j],
  91075. value: value
  91076. });
  91077. }
  91078. else if (lastAnimation) {
  91079. lastAnimation.getKeys()[j].value = value;
  91080. }
  91081. }
  91082. // Finish
  91083. if (!modifyKey && babylonAnimation) {
  91084. babylonAnimation.setKeys(keys);
  91085. targetNode.animations.push(babylonAnimation);
  91086. }
  91087. lastAnimation = babylonAnimation;
  91088. gltfRuntime.scene.stopAnimation(targetNode);
  91089. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  91090. }
  91091. }
  91092. };
  91093. /**
  91094. * Returns the bones transformation matrix
  91095. */
  91096. var configureBoneTransformation = function (node) {
  91097. var mat = null;
  91098. if (node.translation || node.rotation || node.scale) {
  91099. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  91100. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  91101. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  91102. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  91103. }
  91104. else {
  91105. mat = BABYLON.Matrix.FromArray(node.matrix);
  91106. }
  91107. return mat;
  91108. };
  91109. /**
  91110. * Returns the parent bone
  91111. */
  91112. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  91113. // Try to find
  91114. for (var i = 0; i < newSkeleton.bones.length; i++) {
  91115. if (newSkeleton.bones[i].name === jointName) {
  91116. return newSkeleton.bones[i];
  91117. }
  91118. }
  91119. // Not found, search in gltf nodes
  91120. var nodes = gltfRuntime.nodes;
  91121. for (var nde in nodes) {
  91122. var node = nodes[nde];
  91123. if (!node.jointName) {
  91124. continue;
  91125. }
  91126. var children = node.children;
  91127. for (var i = 0; i < children.length; i++) {
  91128. var child = gltfRuntime.nodes[children[i]];
  91129. if (!child.jointName) {
  91130. continue;
  91131. }
  91132. if (child.jointName === jointName) {
  91133. var mat = configureBoneTransformation(node);
  91134. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  91135. bone.id = nde;
  91136. return bone;
  91137. }
  91138. }
  91139. }
  91140. return null;
  91141. };
  91142. /**
  91143. * Returns the appropriate root node
  91144. */
  91145. var getNodeToRoot = function (nodesToRoot, id) {
  91146. for (var i = 0; i < nodesToRoot.length; i++) {
  91147. var nodeToRoot = nodesToRoot[i];
  91148. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  91149. var child = nodeToRoot.node.children[j];
  91150. if (child === id) {
  91151. return nodeToRoot.bone;
  91152. }
  91153. }
  91154. }
  91155. return null;
  91156. };
  91157. /**
  91158. * Returns the node with the joint name
  91159. */
  91160. var getJointNode = function (gltfRuntime, jointName) {
  91161. var nodes = gltfRuntime.nodes;
  91162. var node = nodes[jointName];
  91163. if (node) {
  91164. return {
  91165. node: node,
  91166. id: jointName
  91167. };
  91168. }
  91169. for (var nde in nodes) {
  91170. node = nodes[nde];
  91171. if (node.jointName === jointName) {
  91172. return {
  91173. node: node,
  91174. id: nde
  91175. };
  91176. }
  91177. }
  91178. return null;
  91179. };
  91180. /**
  91181. * Checks if a nodes is in joints
  91182. */
  91183. var nodeIsInJoints = function (skins, id) {
  91184. for (var i = 0; i < skins.jointNames.length; i++) {
  91185. if (skins.jointNames[i] === id) {
  91186. return true;
  91187. }
  91188. }
  91189. return false;
  91190. };
  91191. /**
  91192. * Fills the nodes to root for bones and builds hierarchy
  91193. */
  91194. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  91195. // Creates nodes for root
  91196. for (var nde in gltfRuntime.nodes) {
  91197. var node = gltfRuntime.nodes[nde];
  91198. var id = nde;
  91199. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  91200. continue;
  91201. }
  91202. // Create node to root bone
  91203. var mat = configureBoneTransformation(node);
  91204. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  91205. bone.id = id;
  91206. nodesToRoot.push({ bone: bone, node: node, id: id });
  91207. }
  91208. // Parenting
  91209. for (var i = 0; i < nodesToRoot.length; i++) {
  91210. var nodeToRoot = nodesToRoot[i];
  91211. var children = nodeToRoot.node.children;
  91212. for (var j = 0; j < children.length; j++) {
  91213. var child = null;
  91214. for (var k = 0; k < nodesToRoot.length; k++) {
  91215. if (nodesToRoot[k].id === children[j]) {
  91216. child = nodesToRoot[k];
  91217. break;
  91218. }
  91219. }
  91220. if (child) {
  91221. child.bone._parent = nodeToRoot.bone;
  91222. nodeToRoot.bone.children.push(child.bone);
  91223. }
  91224. }
  91225. }
  91226. };
  91227. /**
  91228. * Imports a skeleton
  91229. */
  91230. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  91231. if (!newSkeleton) {
  91232. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  91233. }
  91234. if (!skins.babylonSkeleton) {
  91235. return newSkeleton;
  91236. }
  91237. // Find the root bones
  91238. var nodesToRoot = [];
  91239. var nodesToRootToAdd = [];
  91240. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  91241. newSkeleton.bones = [];
  91242. // Joints
  91243. for (var i = 0; i < skins.jointNames.length; i++) {
  91244. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  91245. if (!jointNode) {
  91246. continue;
  91247. }
  91248. var node = jointNode.node;
  91249. if (!node) {
  91250. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  91251. continue;
  91252. }
  91253. var id = jointNode.id;
  91254. // Optimize, if the bone already exists...
  91255. var existingBone = gltfRuntime.scene.getBoneByID(id);
  91256. if (existingBone) {
  91257. newSkeleton.bones.push(existingBone);
  91258. continue;
  91259. }
  91260. // Search for parent bone
  91261. var foundBone = false;
  91262. var parentBone = null;
  91263. for (var j = 0; j < i; j++) {
  91264. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  91265. if (!jointNode_1) {
  91266. continue;
  91267. }
  91268. var joint = jointNode_1.node;
  91269. if (!joint) {
  91270. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  91271. continue;
  91272. }
  91273. var children = joint.children;
  91274. if (!children) {
  91275. continue;
  91276. }
  91277. foundBone = false;
  91278. for (var k = 0; k < children.length; k++) {
  91279. if (children[k] === id) {
  91280. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  91281. foundBone = true;
  91282. break;
  91283. }
  91284. }
  91285. if (foundBone) {
  91286. break;
  91287. }
  91288. }
  91289. // Create bone
  91290. var mat = configureBoneTransformation(node);
  91291. if (!parentBone && nodesToRoot.length > 0) {
  91292. parentBone = getNodeToRoot(nodesToRoot, id);
  91293. if (parentBone) {
  91294. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  91295. nodesToRootToAdd.push(parentBone);
  91296. }
  91297. }
  91298. }
  91299. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  91300. bone.id = id;
  91301. }
  91302. // Polish
  91303. var bones = newSkeleton.bones;
  91304. newSkeleton.bones = [];
  91305. for (var i = 0; i < skins.jointNames.length; i++) {
  91306. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  91307. if (!jointNode) {
  91308. continue;
  91309. }
  91310. for (var j = 0; j < bones.length; j++) {
  91311. if (bones[j].id === jointNode.id) {
  91312. newSkeleton.bones.push(bones[j]);
  91313. break;
  91314. }
  91315. }
  91316. }
  91317. newSkeleton.prepare();
  91318. // Finish
  91319. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  91320. newSkeleton.bones.push(nodesToRootToAdd[i]);
  91321. }
  91322. return newSkeleton;
  91323. };
  91324. /**
  91325. * Imports a mesh and its geometries
  91326. */
  91327. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  91328. if (!newMesh) {
  91329. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  91330. newMesh.id = id;
  91331. }
  91332. if (!node.babylonNode) {
  91333. return newMesh;
  91334. }
  91335. var subMaterials = [];
  91336. var vertexData = null;
  91337. var verticesStarts = new Array();
  91338. var verticesCounts = new Array();
  91339. var indexStarts = new Array();
  91340. var indexCounts = new Array();
  91341. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  91342. var meshID = meshes[meshIndex];
  91343. var mesh = gltfRuntime.meshes[meshID];
  91344. if (!mesh) {
  91345. continue;
  91346. }
  91347. // Positions, normals and UVs
  91348. for (var i = 0; i < mesh.primitives.length; i++) {
  91349. // Temporary vertex data
  91350. var tempVertexData = new BABYLON.VertexData();
  91351. var primitive = mesh.primitives[i];
  91352. if (primitive.mode !== 4) {
  91353. // continue;
  91354. }
  91355. var attributes = primitive.attributes;
  91356. var accessor = null;
  91357. var buffer = null;
  91358. // Set positions, normal and uvs
  91359. for (var semantic in attributes) {
  91360. // Link accessor and buffer view
  91361. accessor = gltfRuntime.accessors[attributes[semantic]];
  91362. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  91363. if (semantic === "NORMAL") {
  91364. tempVertexData.normals = new Float32Array(buffer.length);
  91365. tempVertexData.normals.set(buffer);
  91366. }
  91367. else if (semantic === "POSITION") {
  91368. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  91369. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  91370. for (var j = 0; j < buffer.length; j += 4) {
  91371. tempVertexData.positions[j] = buffer[j];
  91372. tempVertexData.positions[j + 1] = buffer[j + 1];
  91373. tempVertexData.positions[j + 2] = buffer[j + 2];
  91374. }
  91375. }
  91376. else {
  91377. tempVertexData.positions = new Float32Array(buffer.length);
  91378. tempVertexData.positions.set(buffer);
  91379. }
  91380. verticesCounts.push(tempVertexData.positions.length);
  91381. }
  91382. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  91383. var channel = Number(semantic.split("_")[1]);
  91384. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  91385. var uvs = new Float32Array(buffer.length);
  91386. uvs.set(buffer);
  91387. normalizeUVs(uvs);
  91388. tempVertexData.set(uvs, uvKind);
  91389. }
  91390. else if (semantic === "JOINT") {
  91391. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  91392. tempVertexData.matricesIndices.set(buffer);
  91393. }
  91394. else if (semantic === "WEIGHT") {
  91395. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  91396. tempVertexData.matricesWeights.set(buffer);
  91397. }
  91398. else if (semantic === "COLOR") {
  91399. tempVertexData.colors = new Float32Array(buffer.length);
  91400. tempVertexData.colors.set(buffer);
  91401. }
  91402. }
  91403. // Indices
  91404. accessor = gltfRuntime.accessors[primitive.indices];
  91405. if (accessor) {
  91406. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  91407. tempVertexData.indices = new Int32Array(buffer.length);
  91408. tempVertexData.indices.set(buffer);
  91409. indexCounts.push(tempVertexData.indices.length);
  91410. }
  91411. else {
  91412. // Set indices on the fly
  91413. var indices = [];
  91414. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  91415. indices.push(j);
  91416. }
  91417. tempVertexData.indices = new Int32Array(indices);
  91418. indexCounts.push(tempVertexData.indices.length);
  91419. }
  91420. if (!vertexData) {
  91421. vertexData = tempVertexData;
  91422. }
  91423. else {
  91424. vertexData.merge(tempVertexData);
  91425. }
  91426. // Sub material
  91427. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  91428. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  91429. // Update vertices start and index start
  91430. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  91431. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  91432. }
  91433. }
  91434. var material;
  91435. if (subMaterials.length > 1) {
  91436. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  91437. material.subMaterials = subMaterials;
  91438. }
  91439. else {
  91440. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  91441. }
  91442. if (subMaterials.length === 1) {
  91443. material = subMaterials[0];
  91444. }
  91445. if (!newMesh.material) {
  91446. newMesh.material = material;
  91447. }
  91448. // Apply geometry
  91449. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  91450. newMesh.computeWorldMatrix(true);
  91451. // Apply submeshes
  91452. newMesh.subMeshes = [];
  91453. var index = 0;
  91454. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  91455. var meshID = meshes[meshIndex];
  91456. var mesh = gltfRuntime.meshes[meshID];
  91457. if (!mesh) {
  91458. continue;
  91459. }
  91460. for (var i = 0; i < mesh.primitives.length; i++) {
  91461. if (mesh.primitives[i].mode !== 4) {
  91462. //continue;
  91463. }
  91464. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  91465. index++;
  91466. }
  91467. }
  91468. // Finish
  91469. return newMesh;
  91470. };
  91471. /**
  91472. * Configure node transformation from position, rotation and scaling
  91473. */
  91474. var configureNode = function (newNode, position, rotation, scaling) {
  91475. if (newNode.position) {
  91476. newNode.position = position;
  91477. }
  91478. if (newNode.rotationQuaternion || newNode.rotation) {
  91479. newNode.rotationQuaternion = rotation;
  91480. }
  91481. if (newNode.scaling) {
  91482. newNode.scaling = scaling;
  91483. }
  91484. };
  91485. /**
  91486. * Configures node from transformation matrix
  91487. */
  91488. var configureNodeFromMatrix = function (newNode, node, parent) {
  91489. if (node.matrix) {
  91490. var position = new BABYLON.Vector3(0, 0, 0);
  91491. var rotation = new BABYLON.Quaternion();
  91492. var scaling = new BABYLON.Vector3(0, 0, 0);
  91493. var mat = BABYLON.Matrix.FromArray(node.matrix);
  91494. mat.decompose(scaling, rotation, position);
  91495. configureNode(newNode, position, rotation, scaling);
  91496. }
  91497. else if (node.translation && node.rotation && node.scale) {
  91498. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  91499. }
  91500. newNode.computeWorldMatrix(true);
  91501. };
  91502. /**
  91503. * Imports a node
  91504. */
  91505. var importNode = function (gltfRuntime, node, id, parent) {
  91506. var lastNode = null;
  91507. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  91508. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  91509. return null;
  91510. }
  91511. }
  91512. // Meshes
  91513. if (node.skin) {
  91514. if (node.meshes) {
  91515. var skin = gltfRuntime.skins[node.skin];
  91516. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  91517. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  91518. if (newMesh.skeleton === null) {
  91519. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  91520. if (!skin.babylonSkeleton) {
  91521. skin.babylonSkeleton = newMesh.skeleton;
  91522. }
  91523. }
  91524. lastNode = newMesh;
  91525. }
  91526. }
  91527. else if (node.meshes) {
  91528. /**
  91529. * Improve meshes property
  91530. */
  91531. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  91532. lastNode = newMesh;
  91533. }
  91534. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  91535. var light = gltfRuntime.lights[node.light];
  91536. if (light) {
  91537. if (light.type === "ambient") {
  91538. var ambienLight = light[light.type];
  91539. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91540. hemiLight.name = node.name || "";
  91541. if (ambienLight.color) {
  91542. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  91543. }
  91544. lastNode = hemiLight;
  91545. }
  91546. else if (light.type === "directional") {
  91547. var directionalLight = light[light.type];
  91548. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91549. dirLight.name = node.name || "";
  91550. if (directionalLight.color) {
  91551. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  91552. }
  91553. lastNode = dirLight;
  91554. }
  91555. else if (light.type === "point") {
  91556. var pointLight = light[light.type];
  91557. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91558. ptLight.name = node.name || "";
  91559. if (pointLight.color) {
  91560. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  91561. }
  91562. lastNode = ptLight;
  91563. }
  91564. else if (light.type === "spot") {
  91565. var spotLight = light[light.type];
  91566. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  91567. spLight.name = node.name || "";
  91568. if (spotLight.color) {
  91569. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  91570. }
  91571. if (spotLight.fallOfAngle) {
  91572. spLight.angle = spotLight.fallOfAngle;
  91573. }
  91574. if (spotLight.fallOffExponent) {
  91575. spLight.exponent = spotLight.fallOffExponent;
  91576. }
  91577. lastNode = spLight;
  91578. }
  91579. }
  91580. }
  91581. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  91582. var camera = gltfRuntime.cameras[node.camera];
  91583. if (camera) {
  91584. if (camera.type === "orthographic") {
  91585. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91586. orthoCamera.name = node.name || "";
  91587. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  91588. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  91589. lastNode = orthoCamera;
  91590. }
  91591. else if (camera.type === "perspective") {
  91592. var perspectiveCamera = camera[camera.type];
  91593. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91594. persCamera.name = node.name || "";
  91595. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  91596. if (!perspectiveCamera.aspectRatio) {
  91597. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  91598. }
  91599. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  91600. persCamera.maxZ = perspectiveCamera.zfar;
  91601. persCamera.minZ = perspectiveCamera.znear;
  91602. }
  91603. lastNode = persCamera;
  91604. }
  91605. }
  91606. }
  91607. // Empty node
  91608. if (!node.jointName) {
  91609. if (node.babylonNode) {
  91610. return node.babylonNode;
  91611. }
  91612. else if (lastNode === null) {
  91613. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  91614. node.babylonNode = dummy;
  91615. lastNode = dummy;
  91616. }
  91617. }
  91618. if (lastNode !== null) {
  91619. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  91620. configureNodeFromMatrix(lastNode, node, parent);
  91621. }
  91622. else {
  91623. var translation = node.translation || [0, 0, 0];
  91624. var rotation = node.rotation || [0, 0, 0, 1];
  91625. var scale = node.scale || [1, 1, 1];
  91626. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  91627. }
  91628. lastNode.updateCache(true);
  91629. node.babylonNode = lastNode;
  91630. }
  91631. return lastNode;
  91632. };
  91633. /**
  91634. * Traverses nodes and creates them
  91635. */
  91636. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  91637. if (meshIncluded === void 0) { meshIncluded = false; }
  91638. var node = gltfRuntime.nodes[id];
  91639. var newNode = null;
  91640. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  91641. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  91642. meshIncluded = true;
  91643. }
  91644. else {
  91645. meshIncluded = false;
  91646. }
  91647. }
  91648. else {
  91649. meshIncluded = true;
  91650. }
  91651. if (!node.jointName && meshIncluded) {
  91652. newNode = importNode(gltfRuntime, node, id, parent);
  91653. if (newNode !== null) {
  91654. newNode.id = id;
  91655. newNode.parent = parent;
  91656. }
  91657. }
  91658. if (node.children) {
  91659. for (var i = 0; i < node.children.length; i++) {
  91660. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  91661. }
  91662. }
  91663. };
  91664. /**
  91665. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  91666. */
  91667. var postLoad = function (gltfRuntime) {
  91668. // Nodes
  91669. var currentScene = gltfRuntime.currentScene;
  91670. if (currentScene) {
  91671. for (var i = 0; i < currentScene.nodes.length; i++) {
  91672. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91673. }
  91674. }
  91675. else {
  91676. for (var thing in gltfRuntime.scenes) {
  91677. currentScene = gltfRuntime.scenes[thing];
  91678. for (var i = 0; i < currentScene.nodes.length; i++) {
  91679. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91680. }
  91681. }
  91682. }
  91683. // Set animations
  91684. loadAnimations(gltfRuntime);
  91685. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  91686. var skeleton = gltfRuntime.scene.skeletons[i];
  91687. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  91688. }
  91689. };
  91690. /**
  91691. * onBind shaderrs callback to set uniforms and matrices
  91692. */
  91693. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  91694. var materialValues = material.values || technique.parameters;
  91695. for (var unif in unTreatedUniforms) {
  91696. var uniform = unTreatedUniforms[unif];
  91697. var type = uniform.type;
  91698. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  91699. if (uniform.semantic && !uniform.source && !uniform.node) {
  91700. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  91701. }
  91702. else if (uniform.semantic && (uniform.source || uniform.node)) {
  91703. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  91704. if (source === null) {
  91705. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  91706. }
  91707. if (source === null) {
  91708. continue;
  91709. }
  91710. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  91711. }
  91712. }
  91713. else {
  91714. var value = materialValues[technique.uniforms[unif]];
  91715. if (!value) {
  91716. continue;
  91717. }
  91718. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  91719. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  91720. if (texture === null || texture === undefined) {
  91721. continue;
  91722. }
  91723. shaderMaterial.getEffect().setTexture(unif, texture);
  91724. }
  91725. else {
  91726. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  91727. }
  91728. }
  91729. }
  91730. onSuccess(shaderMaterial);
  91731. };
  91732. /**
  91733. * Prepare uniforms to send the only one time
  91734. * Loads the appropriate textures
  91735. */
  91736. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  91737. var materialValues = material.values || technique.parameters;
  91738. var techniqueUniforms = technique.uniforms;
  91739. /**
  91740. * Prepare values here (not matrices)
  91741. */
  91742. for (var unif in unTreatedUniforms) {
  91743. var uniform = unTreatedUniforms[unif];
  91744. var type = uniform.type;
  91745. var value = materialValues[techniqueUniforms[unif]];
  91746. if (value === undefined) {
  91747. // In case the value is the same for all materials
  91748. value = uniform.value;
  91749. }
  91750. if (!value) {
  91751. continue;
  91752. }
  91753. var onLoadTexture = function (uniformName) {
  91754. return function (texture) {
  91755. if (uniform.value && uniformName) {
  91756. // Static uniform
  91757. shaderMaterial.setTexture(uniformName, texture);
  91758. delete unTreatedUniforms[uniformName];
  91759. }
  91760. };
  91761. };
  91762. // Texture (sampler2D)
  91763. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  91764. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  91765. }
  91766. else {
  91767. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  91768. // Static uniform
  91769. delete unTreatedUniforms[unif];
  91770. }
  91771. }
  91772. }
  91773. };
  91774. /**
  91775. * Shader compilation failed
  91776. */
  91777. var onShaderCompileError = function (program, shaderMaterial, onError) {
  91778. return function (effect, error) {
  91779. shaderMaterial.dispose(true);
  91780. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  91781. };
  91782. };
  91783. /**
  91784. * Shader compilation success
  91785. */
  91786. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  91787. return function (_) {
  91788. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  91789. shaderMaterial.onBind = function (mesh) {
  91790. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  91791. };
  91792. };
  91793. };
  91794. /**
  91795. * Returns the appropriate uniform if already handled by babylon
  91796. */
  91797. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  91798. for (var unif in technique.uniforms) {
  91799. var uniform = technique.uniforms[unif];
  91800. var uniformParameter = technique.parameters[uniform];
  91801. if (tokenizer.currentIdentifier === unif) {
  91802. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  91803. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  91804. if (transformIndex !== -1) {
  91805. delete unTreatedUniforms[unif];
  91806. return babylonTransforms[transformIndex];
  91807. }
  91808. }
  91809. }
  91810. }
  91811. return tokenizer.currentIdentifier;
  91812. };
  91813. /**
  91814. * All shaders loaded. Create materials one by one
  91815. */
  91816. var importMaterials = function (gltfRuntime) {
  91817. // Create materials
  91818. for (var mat in gltfRuntime.materials) {
  91819. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  91820. }
  91821. };
  91822. /**
  91823. * Implementation of the base glTF spec
  91824. */
  91825. var GLTFLoaderBase = /** @class */ (function () {
  91826. function GLTFLoaderBase() {
  91827. }
  91828. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  91829. var gltfRuntime = {
  91830. extensions: {},
  91831. accessors: {},
  91832. buffers: {},
  91833. bufferViews: {},
  91834. meshes: {},
  91835. lights: {},
  91836. cameras: {},
  91837. nodes: {},
  91838. images: {},
  91839. textures: {},
  91840. shaders: {},
  91841. programs: {},
  91842. samplers: {},
  91843. techniques: {},
  91844. materials: {},
  91845. animations: {},
  91846. skins: {},
  91847. extensionsUsed: [],
  91848. scenes: {},
  91849. buffersCount: 0,
  91850. shaderscount: 0,
  91851. scene: scene,
  91852. rootUrl: rootUrl,
  91853. loadedBufferCount: 0,
  91854. loadedBufferViews: {},
  91855. loadedShaderCount: 0,
  91856. importOnlyMeshes: false,
  91857. dummyNodes: []
  91858. };
  91859. // Parse
  91860. if (parsedData.extensions) {
  91861. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  91862. }
  91863. if (parsedData.extensionsUsed) {
  91864. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  91865. }
  91866. if (parsedData.buffers) {
  91867. parseBuffers(parsedData.buffers, gltfRuntime);
  91868. }
  91869. if (parsedData.bufferViews) {
  91870. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  91871. }
  91872. if (parsedData.accessors) {
  91873. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  91874. }
  91875. if (parsedData.meshes) {
  91876. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  91877. }
  91878. if (parsedData.lights) {
  91879. parseObject(parsedData.lights, "lights", gltfRuntime);
  91880. }
  91881. if (parsedData.cameras) {
  91882. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  91883. }
  91884. if (parsedData.nodes) {
  91885. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  91886. }
  91887. if (parsedData.images) {
  91888. parseObject(parsedData.images, "images", gltfRuntime);
  91889. }
  91890. if (parsedData.textures) {
  91891. parseObject(parsedData.textures, "textures", gltfRuntime);
  91892. }
  91893. if (parsedData.shaders) {
  91894. parseShaders(parsedData.shaders, gltfRuntime);
  91895. }
  91896. if (parsedData.programs) {
  91897. parseObject(parsedData.programs, "programs", gltfRuntime);
  91898. }
  91899. if (parsedData.samplers) {
  91900. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  91901. }
  91902. if (parsedData.techniques) {
  91903. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  91904. }
  91905. if (parsedData.materials) {
  91906. parseObject(parsedData.materials, "materials", gltfRuntime);
  91907. }
  91908. if (parsedData.animations) {
  91909. parseObject(parsedData.animations, "animations", gltfRuntime);
  91910. }
  91911. if (parsedData.skins) {
  91912. parseObject(parsedData.skins, "skins", gltfRuntime);
  91913. }
  91914. if (parsedData.scenes) {
  91915. gltfRuntime.scenes = parsedData.scenes;
  91916. }
  91917. if (parsedData.scene && parsedData.scenes) {
  91918. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  91919. }
  91920. return gltfRuntime;
  91921. };
  91922. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  91923. var buffer = gltfRuntime.buffers[id];
  91924. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  91925. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  91926. }
  91927. else {
  91928. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  91929. if (request) {
  91930. onError(request.status + " " + request.statusText);
  91931. }
  91932. });
  91933. }
  91934. };
  91935. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91936. var texture = gltfRuntime.textures[id];
  91937. if (!texture || !texture.source) {
  91938. onError("");
  91939. return;
  91940. }
  91941. if (texture.babylonTexture) {
  91942. onSuccess(null);
  91943. return;
  91944. }
  91945. var source = gltfRuntime.images[texture.source];
  91946. if (BABYLON.Tools.IsBase64(source.uri)) {
  91947. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  91948. }
  91949. else {
  91950. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  91951. if (request) {
  91952. onError(request.status + " " + request.statusText);
  91953. }
  91954. });
  91955. }
  91956. };
  91957. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  91958. var texture = gltfRuntime.textures[id];
  91959. if (texture.babylonTexture) {
  91960. onSuccess(texture.babylonTexture);
  91961. return;
  91962. }
  91963. var sampler = gltfRuntime.samplers[texture.sampler];
  91964. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  91965. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  91966. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  91967. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  91968. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  91969. var blob = new Blob([buffer]);
  91970. var blobURL = URL.createObjectURL(blob);
  91971. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  91972. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  91973. if (sampler.wrapS !== undefined) {
  91974. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  91975. }
  91976. if (sampler.wrapT !== undefined) {
  91977. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  91978. }
  91979. newTexture.name = id;
  91980. texture.babylonTexture = newTexture;
  91981. onSuccess(newTexture);
  91982. };
  91983. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91984. var shader = gltfRuntime.shaders[id];
  91985. if (BABYLON.Tools.IsBase64(shader.uri)) {
  91986. var shaderString = atob(shader.uri.split(",")[1]);
  91987. onSuccess(shaderString);
  91988. }
  91989. else {
  91990. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  91991. if (request) {
  91992. onError(request.status + " " + request.statusText);
  91993. }
  91994. });
  91995. }
  91996. };
  91997. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  91998. var material = gltfRuntime.materials[id];
  91999. if (!material.technique) {
  92000. if (onError) {
  92001. onError("No technique found.");
  92002. }
  92003. return;
  92004. }
  92005. var technique = gltfRuntime.techniques[material.technique];
  92006. if (!technique) {
  92007. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  92008. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  92009. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  92010. onSuccess(defaultMaterial);
  92011. return;
  92012. }
  92013. var program = gltfRuntime.programs[technique.program];
  92014. var states = technique.states;
  92015. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  92016. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  92017. var newVertexShader = "";
  92018. var newPixelShader = "";
  92019. var vertexTokenizer = new Tokenizer(vertexShader);
  92020. var pixelTokenizer = new Tokenizer(pixelShader);
  92021. var unTreatedUniforms = {};
  92022. var uniforms = [];
  92023. var attributes = [];
  92024. var samplers = [];
  92025. // Fill uniform, sampler2D and attributes
  92026. for (var unif in technique.uniforms) {
  92027. var uniform = technique.uniforms[unif];
  92028. var uniformParameter = technique.parameters[uniform];
  92029. unTreatedUniforms[unif] = uniformParameter;
  92030. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  92031. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  92032. if (transformIndex !== -1) {
  92033. uniforms.push(babylonTransforms[transformIndex]);
  92034. delete unTreatedUniforms[unif];
  92035. }
  92036. else {
  92037. uniforms.push(unif);
  92038. }
  92039. }
  92040. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  92041. samplers.push(unif);
  92042. }
  92043. else {
  92044. uniforms.push(unif);
  92045. }
  92046. }
  92047. for (var attr in technique.attributes) {
  92048. var attribute = technique.attributes[attr];
  92049. var attributeParameter = technique.parameters[attribute];
  92050. if (attributeParameter.semantic) {
  92051. attributes.push(getAttribute(attributeParameter));
  92052. }
  92053. }
  92054. // Configure vertex shader
  92055. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  92056. var tokenType = vertexTokenizer.currentToken;
  92057. if (tokenType !== ETokenType.IDENTIFIER) {
  92058. newVertexShader += vertexTokenizer.currentString;
  92059. continue;
  92060. }
  92061. var foundAttribute = false;
  92062. for (var attr in technique.attributes) {
  92063. var attribute = technique.attributes[attr];
  92064. var attributeParameter = technique.parameters[attribute];
  92065. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  92066. newVertexShader += getAttribute(attributeParameter);
  92067. foundAttribute = true;
  92068. break;
  92069. }
  92070. }
  92071. if (foundAttribute) {
  92072. continue;
  92073. }
  92074. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  92075. }
  92076. // Configure pixel shader
  92077. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  92078. var tokenType = pixelTokenizer.currentToken;
  92079. if (tokenType !== ETokenType.IDENTIFIER) {
  92080. newPixelShader += pixelTokenizer.currentString;
  92081. continue;
  92082. }
  92083. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  92084. }
  92085. // Create shader material
  92086. var shaderPath = {
  92087. vertex: program.vertexShader + id,
  92088. fragment: program.fragmentShader + id
  92089. };
  92090. var options = {
  92091. attributes: attributes,
  92092. uniforms: uniforms,
  92093. samplers: samplers,
  92094. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  92095. };
  92096. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  92097. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  92098. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  92099. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  92100. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  92101. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  92102. if (states && states.functions) {
  92103. var functions = states.functions;
  92104. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  92105. shaderMaterial.backFaceCulling = false;
  92106. }
  92107. var blendFunc = functions.blendFuncSeparate;
  92108. if (blendFunc) {
  92109. 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) {
  92110. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  92111. }
  92112. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  92113. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  92114. }
  92115. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  92116. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  92117. }
  92118. 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) {
  92119. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  92120. }
  92121. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  92122. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  92123. }
  92124. 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) {
  92125. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  92126. }
  92127. }
  92128. }
  92129. };
  92130. return GLTFLoaderBase;
  92131. }());
  92132. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  92133. /**
  92134. * glTF V1 Loader
  92135. */
  92136. var GLTFLoader = /** @class */ (function () {
  92137. function GLTFLoader() {
  92138. // #region Stubs for IGLTFLoader interface
  92139. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  92140. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  92141. this.compileMaterials = false;
  92142. this.useClipPlane = false;
  92143. this.compileShadowGenerators = false;
  92144. this.onDisposeObservable = new BABYLON.Observable();
  92145. this.onMeshLoadedObservable = new BABYLON.Observable();
  92146. this.onTextureLoadedObservable = new BABYLON.Observable();
  92147. this.onMaterialLoadedObservable = new BABYLON.Observable();
  92148. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  92149. this.onCompleteObservable = new BABYLON.Observable();
  92150. this.onExtensionLoadedObservable = new BABYLON.Observable();
  92151. this.state = null;
  92152. }
  92153. GLTFLoader.RegisterExtension = function (extension) {
  92154. if (GLTFLoader.Extensions[extension.name]) {
  92155. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  92156. return;
  92157. }
  92158. GLTFLoader.Extensions[extension.name] = extension;
  92159. };
  92160. GLTFLoader.prototype.dispose = function () { };
  92161. // #endregion
  92162. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  92163. var _this = this;
  92164. scene.useRightHandedSystem = true;
  92165. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  92166. gltfRuntime.importOnlyMeshes = true;
  92167. if (meshesNames === "") {
  92168. gltfRuntime.importMeshesNames = [];
  92169. }
  92170. else if (typeof meshesNames === "string") {
  92171. gltfRuntime.importMeshesNames = [meshesNames];
  92172. }
  92173. else if (meshesNames && !(meshesNames instanceof Array)) {
  92174. gltfRuntime.importMeshesNames = [meshesNames];
  92175. }
  92176. else {
  92177. gltfRuntime.importMeshesNames = [];
  92178. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  92179. }
  92180. // Create nodes
  92181. _this._createNodes(gltfRuntime);
  92182. var meshes = new Array();
  92183. var skeletons = new Array();
  92184. // Fill arrays of meshes and skeletons
  92185. for (var nde in gltfRuntime.nodes) {
  92186. var node = gltfRuntime.nodes[nde];
  92187. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  92188. meshes.push(node.babylonNode);
  92189. }
  92190. }
  92191. for (var skl in gltfRuntime.skins) {
  92192. var skin = gltfRuntime.skins[skl];
  92193. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  92194. skeletons.push(skin.babylonSkeleton);
  92195. }
  92196. }
  92197. // Load buffers, shaders, materials, etc.
  92198. _this._loadBuffersAsync(gltfRuntime, function () {
  92199. _this._loadShadersAsync(gltfRuntime, function () {
  92200. importMaterials(gltfRuntime);
  92201. postLoad(gltfRuntime);
  92202. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  92203. onSuccess(meshes, [], skeletons);
  92204. }
  92205. });
  92206. }, onProgress);
  92207. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  92208. onSuccess(meshes, [], skeletons);
  92209. }
  92210. }, onError);
  92211. return true;
  92212. };
  92213. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  92214. var _this = this;
  92215. return new Promise(function (resolve, reject) {
  92216. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  92217. resolve({
  92218. meshes: meshes,
  92219. particleSystems: particleSystems,
  92220. skeletons: skeletons
  92221. });
  92222. }, onProgress, function (message) {
  92223. reject(new Error(message));
  92224. });
  92225. });
  92226. };
  92227. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  92228. var _this = this;
  92229. scene.useRightHandedSystem = true;
  92230. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  92231. // Load runtime extensios
  92232. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  92233. // Create nodes
  92234. _this._createNodes(gltfRuntime);
  92235. // Load buffers, shaders, materials, etc.
  92236. _this._loadBuffersAsync(gltfRuntime, function () {
  92237. _this._loadShadersAsync(gltfRuntime, function () {
  92238. importMaterials(gltfRuntime);
  92239. postLoad(gltfRuntime);
  92240. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  92241. onSuccess();
  92242. }
  92243. });
  92244. });
  92245. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  92246. onSuccess();
  92247. }
  92248. }, onError);
  92249. }, onError);
  92250. };
  92251. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  92252. var _this = this;
  92253. return new Promise(function (resolve, reject) {
  92254. _this._loadAsync(scene, data, rootUrl, function () {
  92255. resolve();
  92256. }, onProgress, function (message) {
  92257. reject(new Error(message));
  92258. });
  92259. });
  92260. };
  92261. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  92262. var hasShaders = false;
  92263. var processShader = function (sha, shader) {
  92264. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  92265. gltfRuntime.loadedShaderCount++;
  92266. if (shaderString) {
  92267. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  92268. }
  92269. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  92270. onload();
  92271. }
  92272. }, function () {
  92273. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  92274. });
  92275. };
  92276. for (var sha in gltfRuntime.shaders) {
  92277. hasShaders = true;
  92278. var shader = gltfRuntime.shaders[sha];
  92279. if (shader) {
  92280. processShader.bind(this, sha, shader)();
  92281. }
  92282. else {
  92283. BABYLON.Tools.Error("No shader named: " + sha);
  92284. }
  92285. }
  92286. if (!hasShaders) {
  92287. onload();
  92288. }
  92289. };
  92290. ;
  92291. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  92292. var hasBuffers = false;
  92293. var processBuffer = function (buf, buffer) {
  92294. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  92295. gltfRuntime.loadedBufferCount++;
  92296. if (bufferView) {
  92297. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  92298. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  92299. }
  92300. gltfRuntime.loadedBufferViews[buf] = bufferView;
  92301. }
  92302. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  92303. onLoad();
  92304. }
  92305. }, function () {
  92306. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  92307. });
  92308. };
  92309. for (var buf in gltfRuntime.buffers) {
  92310. hasBuffers = true;
  92311. var buffer = gltfRuntime.buffers[buf];
  92312. if (buffer) {
  92313. processBuffer.bind(this, buf, buffer)();
  92314. }
  92315. else {
  92316. BABYLON.Tools.Error("No buffer named: " + buf);
  92317. }
  92318. }
  92319. if (!hasBuffers) {
  92320. onLoad();
  92321. }
  92322. };
  92323. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  92324. var currentScene = gltfRuntime.currentScene;
  92325. if (currentScene) {
  92326. // Only one scene even if multiple scenes are defined
  92327. for (var i = 0; i < currentScene.nodes.length; i++) {
  92328. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  92329. }
  92330. }
  92331. else {
  92332. // Load all scenes
  92333. for (var thing in gltfRuntime.scenes) {
  92334. currentScene = gltfRuntime.scenes[thing];
  92335. for (var i = 0; i < currentScene.nodes.length; i++) {
  92336. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  92337. }
  92338. }
  92339. }
  92340. };
  92341. GLTFLoader.Extensions = {};
  92342. return GLTFLoader;
  92343. }());
  92344. GLTF1.GLTFLoader = GLTFLoader;
  92345. ;
  92346. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  92347. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92348. })(BABYLON || (BABYLON = {}));
  92349. //# sourceMappingURL=babylon.glTFLoader.js.map
  92350. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92351. var BABYLON;
  92352. (function (BABYLON) {
  92353. var GLTF1;
  92354. (function (GLTF1) {
  92355. /**
  92356. * Utils functions for GLTF
  92357. */
  92358. var GLTFUtils = /** @class */ (function () {
  92359. function GLTFUtils() {
  92360. }
  92361. /**
  92362. * Sets the given "parameter" matrix
  92363. * @param scene: the {BABYLON.Scene} object
  92364. * @param source: the source node where to pick the matrix
  92365. * @param parameter: the GLTF technique parameter
  92366. * @param uniformName: the name of the shader's uniform
  92367. * @param shaderMaterial: the shader material
  92368. */
  92369. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  92370. var mat = null;
  92371. if (parameter.semantic === "MODEL") {
  92372. mat = source.getWorldMatrix();
  92373. }
  92374. else if (parameter.semantic === "PROJECTION") {
  92375. mat = scene.getProjectionMatrix();
  92376. }
  92377. else if (parameter.semantic === "VIEW") {
  92378. mat = scene.getViewMatrix();
  92379. }
  92380. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  92381. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  92382. }
  92383. else if (parameter.semantic === "MODELVIEW") {
  92384. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  92385. }
  92386. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  92387. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  92388. }
  92389. else if (parameter.semantic === "MODELINVERSE") {
  92390. mat = source.getWorldMatrix().invert();
  92391. }
  92392. else if (parameter.semantic === "VIEWINVERSE") {
  92393. mat = scene.getViewMatrix().invert();
  92394. }
  92395. else if (parameter.semantic === "PROJECTIONINVERSE") {
  92396. mat = scene.getProjectionMatrix().invert();
  92397. }
  92398. else if (parameter.semantic === "MODELVIEWINVERSE") {
  92399. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  92400. }
  92401. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  92402. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  92403. }
  92404. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  92405. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  92406. }
  92407. else {
  92408. debugger;
  92409. }
  92410. if (mat) {
  92411. switch (parameter.type) {
  92412. case GLTF1.EParameterType.FLOAT_MAT2:
  92413. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  92414. break;
  92415. case GLTF1.EParameterType.FLOAT_MAT3:
  92416. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  92417. break;
  92418. case GLTF1.EParameterType.FLOAT_MAT4:
  92419. shaderMaterial.setMatrix(uniformName, mat);
  92420. break;
  92421. default: break;
  92422. }
  92423. }
  92424. };
  92425. /**
  92426. * Sets the given "parameter" matrix
  92427. * @param shaderMaterial: the shader material
  92428. * @param uniform: the name of the shader's uniform
  92429. * @param value: the value of the uniform
  92430. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  92431. */
  92432. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  92433. switch (type) {
  92434. case GLTF1.EParameterType.FLOAT:
  92435. shaderMaterial.setFloat(uniform, value);
  92436. return true;
  92437. case GLTF1.EParameterType.FLOAT_VEC2:
  92438. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  92439. return true;
  92440. case GLTF1.EParameterType.FLOAT_VEC3:
  92441. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  92442. return true;
  92443. case GLTF1.EParameterType.FLOAT_VEC4:
  92444. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  92445. return true;
  92446. default: return false;
  92447. }
  92448. };
  92449. /**
  92450. * Returns the wrap mode of the texture
  92451. * @param mode: the mode value
  92452. */
  92453. GLTFUtils.GetWrapMode = function (mode) {
  92454. switch (mode) {
  92455. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  92456. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  92457. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  92458. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  92459. }
  92460. };
  92461. /**
  92462. * Returns the byte stride giving an accessor
  92463. * @param accessor: the GLTF accessor objet
  92464. */
  92465. GLTFUtils.GetByteStrideFromType = function (accessor) {
  92466. // Needs this function since "byteStride" isn't requiered in glTF format
  92467. var type = accessor.type;
  92468. switch (type) {
  92469. case "VEC2": return 2;
  92470. case "VEC3": return 3;
  92471. case "VEC4": return 4;
  92472. case "MAT2": return 4;
  92473. case "MAT3": return 9;
  92474. case "MAT4": return 16;
  92475. default: return 1;
  92476. }
  92477. };
  92478. /**
  92479. * Returns the texture filter mode giving a mode value
  92480. * @param mode: the filter mode value
  92481. */
  92482. GLTFUtils.GetTextureFilterMode = function (mode) {
  92483. switch (mode) {
  92484. case GLTF1.ETextureFilterType.LINEAR:
  92485. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  92486. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  92487. case GLTF1.ETextureFilterType.NEAREST:
  92488. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  92489. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  92490. }
  92491. };
  92492. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  92493. var byteOffset = bufferView.byteOffset + byteOffset;
  92494. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  92495. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  92496. throw new Error("Buffer access is out of range");
  92497. }
  92498. var buffer = loadedBufferView.buffer;
  92499. byteOffset += loadedBufferView.byteOffset;
  92500. switch (componentType) {
  92501. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  92502. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  92503. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  92504. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  92505. default: return new Float32Array(buffer, byteOffset, byteLength);
  92506. }
  92507. };
  92508. /**
  92509. * Returns a buffer from its accessor
  92510. * @param gltfRuntime: the GLTF runtime
  92511. * @param accessor: the GLTF accessor
  92512. */
  92513. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  92514. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  92515. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  92516. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  92517. };
  92518. /**
  92519. * Decodes a buffer view into a string
  92520. * @param view: the buffer view
  92521. */
  92522. GLTFUtils.DecodeBufferToText = function (view) {
  92523. var result = "";
  92524. var length = view.byteLength;
  92525. for (var i = 0; i < length; ++i) {
  92526. result += String.fromCharCode(view[i]);
  92527. }
  92528. return result;
  92529. };
  92530. /**
  92531. * Returns the default material of gltf. Related to
  92532. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  92533. * @param scene: the Babylon.js scene
  92534. */
  92535. GLTFUtils.GetDefaultMaterial = function (scene) {
  92536. if (!GLTFUtils._DefaultMaterial) {
  92537. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  92538. "precision highp float;",
  92539. "",
  92540. "uniform mat4 worldView;",
  92541. "uniform mat4 projection;",
  92542. "",
  92543. "attribute vec3 position;",
  92544. "",
  92545. "void main(void)",
  92546. "{",
  92547. " gl_Position = projection * worldView * vec4(position, 1.0);",
  92548. "}"
  92549. ].join("\n");
  92550. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  92551. "precision highp float;",
  92552. "",
  92553. "uniform vec4 u_emission;",
  92554. "",
  92555. "void main(void)",
  92556. "{",
  92557. " gl_FragColor = u_emission;",
  92558. "}"
  92559. ].join("\n");
  92560. var shaderPath = {
  92561. vertex: "GLTFDefaultMaterial",
  92562. fragment: "GLTFDefaultMaterial"
  92563. };
  92564. var options = {
  92565. attributes: ["position"],
  92566. uniforms: ["worldView", "projection", "u_emission"],
  92567. samplers: new Array(),
  92568. needAlphaBlending: false
  92569. };
  92570. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  92571. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  92572. }
  92573. return GLTFUtils._DefaultMaterial;
  92574. };
  92575. // The GLTF default material
  92576. GLTFUtils._DefaultMaterial = null;
  92577. return GLTFUtils;
  92578. }());
  92579. GLTF1.GLTFUtils = GLTFUtils;
  92580. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92581. })(BABYLON || (BABYLON = {}));
  92582. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  92583. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92584. var BABYLON;
  92585. (function (BABYLON) {
  92586. var GLTF1;
  92587. (function (GLTF1) {
  92588. var GLTFLoaderExtension = /** @class */ (function () {
  92589. function GLTFLoaderExtension(name) {
  92590. this._name = name;
  92591. }
  92592. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  92593. get: function () {
  92594. return this._name;
  92595. },
  92596. enumerable: true,
  92597. configurable: true
  92598. });
  92599. /**
  92600. * Defines an override for loading the runtime
  92601. * Return true to stop further extensions from loading the runtime
  92602. */
  92603. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92604. return false;
  92605. };
  92606. /**
  92607. * Defines an onverride for creating gltf runtime
  92608. * Return true to stop further extensions from creating the runtime
  92609. */
  92610. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92611. return false;
  92612. };
  92613. /**
  92614. * Defines an override for loading buffers
  92615. * Return true to stop further extensions from loading this buffer
  92616. */
  92617. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  92618. return false;
  92619. };
  92620. /**
  92621. * Defines an override for loading texture buffers
  92622. * Return true to stop further extensions from loading this texture data
  92623. */
  92624. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92625. return false;
  92626. };
  92627. /**
  92628. * Defines an override for creating textures
  92629. * Return true to stop further extensions from loading this texture
  92630. */
  92631. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  92632. return false;
  92633. };
  92634. /**
  92635. * Defines an override for loading shader strings
  92636. * Return true to stop further extensions from loading this shader data
  92637. */
  92638. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92639. return false;
  92640. };
  92641. /**
  92642. * Defines an override for loading materials
  92643. * Return true to stop further extensions from loading this material
  92644. */
  92645. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92646. return false;
  92647. };
  92648. // ---------
  92649. // Utilities
  92650. // ---------
  92651. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92652. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92653. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  92654. }, function () {
  92655. setTimeout(function () {
  92656. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  92657. });
  92658. });
  92659. };
  92660. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92661. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92662. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  92663. }, function () {
  92664. setTimeout(function () {
  92665. onSuccess();
  92666. });
  92667. });
  92668. };
  92669. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  92670. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92671. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  92672. }, function () {
  92673. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  92674. });
  92675. };
  92676. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  92677. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  92678. };
  92679. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92680. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92681. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  92682. }, function () {
  92683. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  92684. });
  92685. };
  92686. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92687. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92688. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  92689. }, function () {
  92690. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  92691. });
  92692. };
  92693. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92694. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92695. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  92696. }, function () {
  92697. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  92698. });
  92699. };
  92700. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  92701. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92702. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  92703. }, function () {
  92704. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  92705. });
  92706. };
  92707. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  92708. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  92709. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  92710. if (func(loaderExtension)) {
  92711. return;
  92712. }
  92713. }
  92714. defaultFunc();
  92715. };
  92716. return GLTFLoaderExtension;
  92717. }());
  92718. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  92719. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92720. })(BABYLON || (BABYLON = {}));
  92721. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  92722. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92723. var BABYLON;
  92724. (function (BABYLON) {
  92725. var GLTF1;
  92726. (function (GLTF1) {
  92727. var BinaryExtensionBufferName = "binary_glTF";
  92728. ;
  92729. ;
  92730. var GLTFBinaryExtension = /** @class */ (function (_super) {
  92731. __extends(GLTFBinaryExtension, _super);
  92732. function GLTFBinaryExtension() {
  92733. return _super.call(this, "KHR_binary_glTF") || this;
  92734. }
  92735. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92736. var extensionsUsed = data.json.extensionsUsed;
  92737. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  92738. return false;
  92739. }
  92740. this._bin = data.bin;
  92741. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  92742. return true;
  92743. };
  92744. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92745. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  92746. return false;
  92747. }
  92748. if (id !== BinaryExtensionBufferName) {
  92749. return false;
  92750. }
  92751. onSuccess(this._bin);
  92752. return true;
  92753. };
  92754. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92755. var texture = gltfRuntime.textures[id];
  92756. var source = gltfRuntime.images[texture.source];
  92757. if (!source.extensions || !(this.name in source.extensions)) {
  92758. return false;
  92759. }
  92760. var sourceExt = source.extensions[this.name];
  92761. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  92762. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  92763. onSuccess(buffer);
  92764. return true;
  92765. };
  92766. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92767. var shader = gltfRuntime.shaders[id];
  92768. if (!shader.extensions || !(this.name in shader.extensions)) {
  92769. return false;
  92770. }
  92771. var binaryExtensionShader = shader.extensions[this.name];
  92772. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  92773. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  92774. setTimeout(function () {
  92775. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  92776. onSuccess(shaderString);
  92777. });
  92778. return true;
  92779. };
  92780. return GLTFBinaryExtension;
  92781. }(GLTF1.GLTFLoaderExtension));
  92782. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  92783. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  92784. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92785. })(BABYLON || (BABYLON = {}));
  92786. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  92787. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92788. var BABYLON;
  92789. (function (BABYLON) {
  92790. var GLTF1;
  92791. (function (GLTF1) {
  92792. ;
  92793. ;
  92794. ;
  92795. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  92796. __extends(GLTFMaterialsCommonExtension, _super);
  92797. function GLTFMaterialsCommonExtension() {
  92798. return _super.call(this, "KHR_materials_common") || this;
  92799. }
  92800. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92801. if (!gltfRuntime.extensions)
  92802. return false;
  92803. var extension = gltfRuntime.extensions[this.name];
  92804. if (!extension)
  92805. return false;
  92806. // Create lights
  92807. var lights = extension.lights;
  92808. if (lights) {
  92809. for (var thing in lights) {
  92810. var light = lights[thing];
  92811. switch (light.type) {
  92812. case "ambient":
  92813. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  92814. var ambient = light.ambient;
  92815. if (ambient) {
  92816. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  92817. }
  92818. break;
  92819. case "point":
  92820. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  92821. var point = light.point;
  92822. if (point) {
  92823. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  92824. }
  92825. break;
  92826. case "directional":
  92827. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  92828. var directional = light.directional;
  92829. if (directional) {
  92830. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  92831. }
  92832. break;
  92833. case "spot":
  92834. var spot = light.spot;
  92835. if (spot) {
  92836. 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);
  92837. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  92838. }
  92839. break;
  92840. default:
  92841. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  92842. break;
  92843. }
  92844. }
  92845. }
  92846. return false;
  92847. };
  92848. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92849. var material = gltfRuntime.materials[id];
  92850. if (!material || !material.extensions)
  92851. return false;
  92852. var extension = material.extensions[this.name];
  92853. if (!extension)
  92854. return false;
  92855. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  92856. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  92857. if (extension.technique === "CONSTANT") {
  92858. standardMaterial.disableLighting = true;
  92859. }
  92860. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  92861. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  92862. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  92863. // Ambient
  92864. if (typeof extension.values.ambient === "string") {
  92865. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  92866. }
  92867. else {
  92868. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  92869. }
  92870. // Diffuse
  92871. if (typeof extension.values.diffuse === "string") {
  92872. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  92873. }
  92874. else {
  92875. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  92876. }
  92877. // Emission
  92878. if (typeof extension.values.emission === "string") {
  92879. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  92880. }
  92881. else {
  92882. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  92883. }
  92884. // Specular
  92885. if (typeof extension.values.specular === "string") {
  92886. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  92887. }
  92888. else {
  92889. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  92890. }
  92891. return true;
  92892. };
  92893. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  92894. // Create buffer from texture url
  92895. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  92896. // Create texture from buffer
  92897. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  92898. }, onError);
  92899. };
  92900. return GLTFMaterialsCommonExtension;
  92901. }(GLTF1.GLTFLoaderExtension));
  92902. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  92903. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  92904. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92905. })(BABYLON || (BABYLON = {}));
  92906. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  92907. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92908. var BABYLON;
  92909. (function (BABYLON) {
  92910. var GLTF2;
  92911. (function (GLTF2) {
  92912. var ArrayItem = /** @class */ (function () {
  92913. function ArrayItem() {
  92914. }
  92915. ArrayItem.Assign = function (values) {
  92916. if (values) {
  92917. for (var index = 0; index < values.length; index++) {
  92918. values[index]._index = index;
  92919. }
  92920. }
  92921. };
  92922. return ArrayItem;
  92923. }());
  92924. GLTF2.ArrayItem = ArrayItem;
  92925. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92926. })(BABYLON || (BABYLON = {}));
  92927. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  92928. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92929. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  92930. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  92931. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92932. var BABYLON;
  92933. (function (BABYLON) {
  92934. var GLTF2;
  92935. (function (GLTF2) {
  92936. var GLTFLoader = /** @class */ (function () {
  92937. function GLTFLoader() {
  92938. this._completePromises = new Array();
  92939. this._disposed = false;
  92940. this._state = null;
  92941. this._extensions = {};
  92942. this._defaultSampler = {};
  92943. this._requests = new Array();
  92944. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  92945. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  92946. this.compileMaterials = false;
  92947. this.useClipPlane = false;
  92948. this.compileShadowGenerators = false;
  92949. this.onDisposeObservable = new BABYLON.Observable();
  92950. this.onMeshLoadedObservable = new BABYLON.Observable();
  92951. this.onTextureLoadedObservable = new BABYLON.Observable();
  92952. this.onMaterialLoadedObservable = new BABYLON.Observable();
  92953. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  92954. this.onExtensionLoadedObservable = new BABYLON.Observable();
  92955. this.onCompleteObservable = new BABYLON.Observable();
  92956. }
  92957. GLTFLoader._Register = function (name, factory) {
  92958. if (GLTFLoader._Factories[name]) {
  92959. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  92960. return;
  92961. }
  92962. GLTFLoader._Factories[name] = factory;
  92963. // Keep the order of registration so that extensions registered first are called first.
  92964. GLTFLoader._Names.push(name);
  92965. };
  92966. Object.defineProperty(GLTFLoader.prototype, "state", {
  92967. get: function () {
  92968. return this._state;
  92969. },
  92970. enumerable: true,
  92971. configurable: true
  92972. });
  92973. GLTFLoader.prototype.dispose = function () {
  92974. if (this._disposed) {
  92975. return;
  92976. }
  92977. this._disposed = true;
  92978. this.onDisposeObservable.notifyObservers(this);
  92979. this.onDisposeObservable.clear();
  92980. this._clear();
  92981. };
  92982. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  92983. var _this = this;
  92984. return Promise.resolve().then(function () {
  92985. var nodes = null;
  92986. if (meshesNames) {
  92987. var nodeMap_1 = {};
  92988. if (_this._gltf.nodes) {
  92989. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  92990. var node = _a[_i];
  92991. if (node.name) {
  92992. nodeMap_1[node.name] = node;
  92993. }
  92994. }
  92995. }
  92996. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  92997. nodes = names.map(function (name) {
  92998. var node = nodeMap_1[name];
  92999. if (!node) {
  93000. throw new Error("Failed to find node '" + name + "'");
  93001. }
  93002. return node;
  93003. });
  93004. }
  93005. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  93006. return {
  93007. meshes: _this._getMeshes(),
  93008. particleSystems: [],
  93009. skeletons: _this._getSkeletons(),
  93010. };
  93011. });
  93012. });
  93013. };
  93014. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  93015. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  93016. };
  93017. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  93018. var _this = this;
  93019. return Promise.resolve().then(function () {
  93020. _this._loadExtensions();
  93021. _this._babylonScene = scene;
  93022. _this._rootUrl = rootUrl;
  93023. _this._progressCallback = onProgress;
  93024. _this._state = BABYLON.GLTFLoaderState.Loading;
  93025. _this._loadData(data);
  93026. _this._checkExtensions();
  93027. var promises = new Array();
  93028. if (nodes) {
  93029. promises.push(_this._loadNodesAsync(nodes));
  93030. }
  93031. else {
  93032. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  93033. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  93034. }
  93035. if (_this.compileMaterials) {
  93036. promises.push(_this._compileMaterialsAsync());
  93037. }
  93038. if (_this.compileShadowGenerators) {
  93039. promises.push(_this._compileShadowGeneratorsAsync());
  93040. }
  93041. var resultPromise = Promise.all(promises).then(function () {
  93042. _this._state = BABYLON.GLTFLoaderState.Ready;
  93043. _this._startAnimations();
  93044. });
  93045. resultPromise.then(function () {
  93046. _this._rootBabylonMesh.setEnabled(true);
  93047. BABYLON.Tools.SetImmediate(function () {
  93048. if (!_this._disposed) {
  93049. Promise.all(_this._completePromises).then(function () {
  93050. _this._state = BABYLON.GLTFLoaderState.Complete;
  93051. _this.onCompleteObservable.notifyObservers(_this);
  93052. _this.onCompleteObservable.clear();
  93053. _this._clear();
  93054. }).catch(function (error) {
  93055. BABYLON.Tools.Error("glTF Loader: " + error.message);
  93056. _this._clear();
  93057. });
  93058. }
  93059. });
  93060. });
  93061. return resultPromise;
  93062. }).catch(function (error) {
  93063. BABYLON.Tools.Error("glTF Loader: " + error.message);
  93064. _this._clear();
  93065. throw error;
  93066. });
  93067. };
  93068. GLTFLoader.prototype._loadExtensions = function () {
  93069. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  93070. var name_1 = _a[_i];
  93071. var extension = GLTFLoader._Factories[name_1](this);
  93072. this._extensions[name_1] = extension;
  93073. this.onExtensionLoadedObservable.notifyObservers(extension);
  93074. }
  93075. this.onExtensionLoadedObservable.clear();
  93076. };
  93077. GLTFLoader.prototype._loadData = function (data) {
  93078. this._gltf = data.json;
  93079. this._setupData();
  93080. if (data.bin) {
  93081. var buffers = this._gltf.buffers;
  93082. if (buffers && buffers[0] && !buffers[0].uri) {
  93083. var binaryBuffer = buffers[0];
  93084. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  93085. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  93086. }
  93087. binaryBuffer._data = Promise.resolve(data.bin);
  93088. }
  93089. else {
  93090. BABYLON.Tools.Warn("Unexpected BIN chunk");
  93091. }
  93092. }
  93093. };
  93094. GLTFLoader.prototype._setupData = function () {
  93095. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  93096. GLTF2.ArrayItem.Assign(this._gltf.animations);
  93097. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  93098. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  93099. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  93100. GLTF2.ArrayItem.Assign(this._gltf.images);
  93101. GLTF2.ArrayItem.Assign(this._gltf.materials);
  93102. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  93103. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  93104. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  93105. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  93106. GLTF2.ArrayItem.Assign(this._gltf.skins);
  93107. GLTF2.ArrayItem.Assign(this._gltf.textures);
  93108. if (this._gltf.nodes) {
  93109. var nodeParents = {};
  93110. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  93111. var node = _a[_i];
  93112. if (node.children) {
  93113. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  93114. var index = _c[_b];
  93115. nodeParents[index] = node._index;
  93116. }
  93117. }
  93118. }
  93119. var rootNode = this._createRootNode();
  93120. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  93121. var node = _e[_d];
  93122. var parentIndex = nodeParents[node._index];
  93123. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  93124. }
  93125. }
  93126. };
  93127. GLTFLoader.prototype._checkExtensions = function () {
  93128. if (this._gltf.extensionsRequired) {
  93129. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  93130. var name_2 = _a[_i];
  93131. var extension = this._extensions[name_2];
  93132. if (!extension || !extension.enabled) {
  93133. throw new Error("Require extension " + name_2 + " is not available");
  93134. }
  93135. }
  93136. }
  93137. };
  93138. GLTFLoader.prototype._createRootNode = function () {
  93139. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  93140. this._rootBabylonMesh.setEnabled(false);
  93141. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  93142. switch (this.coordinateSystemMode) {
  93143. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  93144. if (!this._babylonScene.useRightHandedSystem) {
  93145. rootNode.rotation = [0, 1, 0, 0];
  93146. rootNode.scale = [1, 1, -1];
  93147. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  93148. }
  93149. break;
  93150. }
  93151. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  93152. this._babylonScene.useRightHandedSystem = true;
  93153. break;
  93154. }
  93155. default: {
  93156. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  93157. }
  93158. }
  93159. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  93160. return rootNode;
  93161. };
  93162. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  93163. var promises = new Array();
  93164. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  93165. var node = nodes_1[_i];
  93166. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  93167. }
  93168. promises.push(this._loadAnimationsAsync());
  93169. return Promise.all(promises).then(function () { });
  93170. };
  93171. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  93172. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  93173. if (promise) {
  93174. return promise;
  93175. }
  93176. var promises = new Array();
  93177. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  93178. var index = _a[_i];
  93179. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  93180. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  93181. }
  93182. promises.push(this._loadAnimationsAsync());
  93183. return Promise.all(promises).then(function () { });
  93184. };
  93185. GLTFLoader.prototype._forEachNodeMesh = function (node, callback) {
  93186. if (node._babylonMesh) {
  93187. callback(node._babylonMesh);
  93188. }
  93189. if (node._primitiveBabylonMeshes) {
  93190. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  93191. var babylonMesh = _a[_i];
  93192. callback(babylonMesh);
  93193. }
  93194. }
  93195. };
  93196. GLTFLoader.prototype._getMeshes = function () {
  93197. var meshes = new Array();
  93198. // Root mesh is always first.
  93199. meshes.push(this._rootBabylonMesh);
  93200. var nodes = this._gltf.nodes;
  93201. if (nodes) {
  93202. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  93203. var node = nodes_2[_i];
  93204. this._forEachNodeMesh(node, function (mesh) {
  93205. meshes.push(mesh);
  93206. });
  93207. }
  93208. }
  93209. return meshes;
  93210. };
  93211. GLTFLoader.prototype._getSkeletons = function () {
  93212. var skeletons = new Array();
  93213. var skins = this._gltf.skins;
  93214. if (skins) {
  93215. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  93216. var skin = skins_1[_i];
  93217. if (skin._babylonSkeleton) {
  93218. skeletons.push(skin._babylonSkeleton);
  93219. }
  93220. }
  93221. }
  93222. return skeletons;
  93223. };
  93224. GLTFLoader.prototype._startAnimations = function () {
  93225. var animations = this._gltf.animations;
  93226. if (!animations) {
  93227. return;
  93228. }
  93229. switch (this.animationStartMode) {
  93230. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  93231. // do nothing
  93232. break;
  93233. }
  93234. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  93235. var animation = animations[0];
  93236. animation._babylonAnimationGroup.start(true);
  93237. break;
  93238. }
  93239. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  93240. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  93241. var animation = animations_1[_i];
  93242. animation._babylonAnimationGroup.start(true);
  93243. }
  93244. break;
  93245. }
  93246. default: {
  93247. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  93248. return;
  93249. }
  93250. }
  93251. };
  93252. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  93253. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  93254. if (promise) {
  93255. return promise;
  93256. }
  93257. if (node._babylonMesh) {
  93258. throw new Error(context + ": Invalid recursive node hierarchy");
  93259. }
  93260. var promises = new Array();
  93261. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  93262. node._babylonMesh = babylonMesh;
  93263. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  93264. node._babylonAnimationTargets.push(babylonMesh);
  93265. GLTFLoader._LoadTransform(node, babylonMesh);
  93266. if (node.mesh != undefined) {
  93267. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  93268. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  93269. }
  93270. if (node.children) {
  93271. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  93272. var index = _a[_i];
  93273. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  93274. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  93275. }
  93276. }
  93277. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  93278. return Promise.all(promises).then(function () { });
  93279. };
  93280. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  93281. // TODO: instancing
  93282. var _this = this;
  93283. var promises = new Array();
  93284. var primitives = mesh.primitives;
  93285. if (!primitives || primitives.length === 0) {
  93286. throw new Error(context + ": Primitives are missing");
  93287. }
  93288. GLTF2.ArrayItem.Assign(primitives);
  93289. if (primitives.length === 1) {
  93290. var primitive = primitives[0];
  93291. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  93292. }
  93293. else {
  93294. node._primitiveBabylonMeshes = [];
  93295. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  93296. var primitive = primitives_1[_i];
  93297. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  93298. node._primitiveBabylonMeshes.push(babylonMesh);
  93299. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  93300. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  93301. }
  93302. }
  93303. if (node.skin != undefined) {
  93304. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  93305. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  93306. }
  93307. return Promise.all(promises).then(function () {
  93308. _this._forEachNodeMesh(node, function (babylonMesh) {
  93309. babylonMesh._refreshBoundingInfo(true);
  93310. });
  93311. });
  93312. };
  93313. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  93314. var _this = this;
  93315. var promises = new Array();
  93316. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  93317. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  93318. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  93319. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  93320. }));
  93321. if (primitive.material == undefined) {
  93322. babylonMesh.material = this._getDefaultMaterial();
  93323. }
  93324. else {
  93325. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  93326. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, function (babylonMaterial) {
  93327. babylonMesh.material = babylonMaterial;
  93328. }));
  93329. }
  93330. return Promise.all(promises).then(function () { });
  93331. };
  93332. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  93333. var _this = this;
  93334. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  93335. if (promise) {
  93336. return promise;
  93337. }
  93338. var attributes = primitive.attributes;
  93339. if (!attributes) {
  93340. throw new Error(context + ": Attributes are missing");
  93341. }
  93342. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  93343. // TODO: handle other primitive modes
  93344. throw new Error(context + ": Mode (" + primitive.mode + ") is not currently supported");
  93345. }
  93346. var promises = new Array();
  93347. var babylonVertexData = new BABYLON.VertexData();
  93348. if (primitive.indices == undefined) {
  93349. var positionAccessorIndex = attributes["POSITION"];
  93350. if (positionAccessorIndex != undefined) {
  93351. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  93352. babylonVertexData.indices = new Uint32Array(accessor.count);
  93353. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  93354. babylonVertexData.indices[i] = i;
  93355. }
  93356. }
  93357. }
  93358. else {
  93359. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  93360. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  93361. babylonVertexData.indices = data;
  93362. }));
  93363. }
  93364. var loadAttribute = function (attribute, kind) {
  93365. if (attributes[attribute] == undefined) {
  93366. return;
  93367. }
  93368. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  93369. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  93370. babylonMesh._delayInfo.push(kind);
  93371. }
  93372. if (attribute === "COLOR_0") {
  93373. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  93374. babylonMesh.hasVertexAlpha = true;
  93375. }
  93376. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  93377. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  93378. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  93379. if (attribute === "COLOR_0" && accessor.type === "VEC3") {
  93380. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  93381. }
  93382. babylonVertexData.set(attributeData, kind);
  93383. }));
  93384. };
  93385. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  93386. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  93387. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  93388. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  93389. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  93390. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  93391. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  93392. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  93393. return Promise.all(promises).then(function () {
  93394. return babylonVertexData;
  93395. });
  93396. };
  93397. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  93398. if (!primitive.targets) {
  93399. return;
  93400. }
  93401. if (node._numMorphTargets == undefined) {
  93402. node._numMorphTargets = primitive.targets.length;
  93403. }
  93404. else if (primitive.targets.length !== node._numMorphTargets) {
  93405. throw new Error(context + ": Primitives do not have the same number of targets");
  93406. }
  93407. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  93408. for (var index = 0; index < primitive.targets.length; index++) {
  93409. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  93410. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  93411. // TODO: tell the target whether it has positions, normals, tangents
  93412. }
  93413. };
  93414. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  93415. if (!primitive.targets) {
  93416. return Promise.resolve();
  93417. }
  93418. var promises = new Array();
  93419. var morphTargetManager = babylonMesh.morphTargetManager;
  93420. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  93421. var babylonMorphTarget = morphTargetManager.getTarget(index);
  93422. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  93423. }
  93424. return Promise.all(promises).then(function () { });
  93425. };
  93426. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  93427. var _this = this;
  93428. var promises = new Array();
  93429. var loadAttribute = function (attribute, setData) {
  93430. if (attributes[attribute] == undefined) {
  93431. return;
  93432. }
  93433. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  93434. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  93435. setData(data);
  93436. }));
  93437. };
  93438. loadAttribute("POSITION", function (data) {
  93439. if (babylonVertexData.positions) {
  93440. for (var i = 0; i < data.length; i++) {
  93441. data[i] += babylonVertexData.positions[i];
  93442. }
  93443. babylonMorphTarget.setPositions(data);
  93444. }
  93445. });
  93446. loadAttribute("NORMAL", function (data) {
  93447. if (babylonVertexData.normals) {
  93448. for (var i = 0; i < data.length; i++) {
  93449. data[i] += babylonVertexData.normals[i];
  93450. }
  93451. babylonMorphTarget.setNormals(data);
  93452. }
  93453. });
  93454. loadAttribute("TANGENT", function (data) {
  93455. if (babylonVertexData.tangents) {
  93456. // Tangent data for morph targets is stored as xyz delta.
  93457. // The vertexData.tangent is stored as xyzw.
  93458. // So we need to skip every fourth vertexData.tangent.
  93459. for (var i = 0, j = 0; i < data.length; i++) {
  93460. data[i] += babylonVertexData.tangents[j++];
  93461. if ((i + 1) % 3 == 0) {
  93462. j++;
  93463. }
  93464. }
  93465. babylonMorphTarget.setTangents(data);
  93466. }
  93467. });
  93468. return Promise.all(promises).then(function () { });
  93469. };
  93470. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  93471. if (accessor.componentType == 5126 /* FLOAT */) {
  93472. return data;
  93473. }
  93474. var factor = 1;
  93475. if (accessor.normalized) {
  93476. switch (accessor.componentType) {
  93477. case 5121 /* UNSIGNED_BYTE */: {
  93478. factor = 1 / 255;
  93479. break;
  93480. }
  93481. case 5123 /* UNSIGNED_SHORT */: {
  93482. factor = 1 / 65535;
  93483. break;
  93484. }
  93485. default: {
  93486. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  93487. }
  93488. }
  93489. }
  93490. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  93491. for (var i = 0; i < result.length; i++) {
  93492. result[i] = data[i] * factor;
  93493. }
  93494. return result;
  93495. };
  93496. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  93497. var result = new Float32Array(data.length / 3 * 4);
  93498. var offset = 0;
  93499. for (var i = 0; i < result.length; i++) {
  93500. if ((i + 1) % 4 === 0) {
  93501. result[i] = 1;
  93502. }
  93503. else {
  93504. result[i] = data[offset++];
  93505. }
  93506. }
  93507. return result;
  93508. };
  93509. GLTFLoader._LoadTransform = function (node, babylonNode) {
  93510. var position = BABYLON.Vector3.Zero();
  93511. var rotation = BABYLON.Quaternion.Identity();
  93512. var scaling = BABYLON.Vector3.One();
  93513. if (node.matrix) {
  93514. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  93515. matrix.decompose(scaling, rotation, position);
  93516. }
  93517. else {
  93518. if (node.translation)
  93519. position = BABYLON.Vector3.FromArray(node.translation);
  93520. if (node.rotation)
  93521. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  93522. if (node.scale)
  93523. scaling = BABYLON.Vector3.FromArray(node.scale);
  93524. }
  93525. babylonNode.position = position;
  93526. babylonNode.rotationQuaternion = rotation;
  93527. babylonNode.scaling = scaling;
  93528. };
  93529. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  93530. var _this = this;
  93531. var assignSkeleton = function () {
  93532. _this._forEachNodeMesh(node, function (babylonMesh) {
  93533. babylonMesh.skeleton = skin._babylonSkeleton;
  93534. });
  93535. node._babylonMesh.parent = _this._rootBabylonMesh;
  93536. node._babylonMesh.position = BABYLON.Vector3.Zero();
  93537. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  93538. node._babylonMesh.scaling = BABYLON.Vector3.One();
  93539. };
  93540. if (skin._loaded) {
  93541. return skin._loaded.then(function () {
  93542. assignSkeleton();
  93543. });
  93544. }
  93545. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  93546. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  93547. var skeletonId = "skeleton" + skin._index;
  93548. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  93549. skin._babylonSkeleton = babylonSkeleton;
  93550. _this._loadBones(context, skin, inverseBindMatricesData);
  93551. assignSkeleton();
  93552. }));
  93553. };
  93554. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  93555. if (skin.inverseBindMatrices == undefined) {
  93556. return Promise.resolve(null);
  93557. }
  93558. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  93559. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  93560. return data;
  93561. });
  93562. };
  93563. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  93564. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  93565. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  93566. node._babylonAnimationTargets.push(babylonBone);
  93567. return babylonBone;
  93568. };
  93569. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  93570. var babylonBones = {};
  93571. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  93572. var index = _a[_i];
  93573. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  93574. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  93575. }
  93576. };
  93577. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  93578. var babylonBone = babylonBones[node._index];
  93579. if (babylonBone) {
  93580. return babylonBone;
  93581. }
  93582. var boneIndex = skin.joints.indexOf(node._index);
  93583. var baseMatrix = BABYLON.Matrix.Identity();
  93584. if (inverseBindMatricesData && boneIndex !== -1) {
  93585. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  93586. baseMatrix.invertToRef(baseMatrix);
  93587. }
  93588. var babylonParentBone = null;
  93589. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  93590. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  93591. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  93592. }
  93593. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  93594. babylonBones[node._index] = babylonBone;
  93595. return babylonBone;
  93596. };
  93597. GLTFLoader.prototype._getNodeMatrix = function (node) {
  93598. return node.matrix ?
  93599. BABYLON.Matrix.FromArray(node.matrix) :
  93600. 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());
  93601. };
  93602. GLTFLoader.prototype._loadAnimationsAsync = function () {
  93603. var animations = this._gltf.animations;
  93604. if (!animations) {
  93605. return Promise.resolve();
  93606. }
  93607. var promises = new Array();
  93608. for (var index = 0; index < animations.length; index++) {
  93609. var animation = animations[index];
  93610. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  93611. }
  93612. return Promise.all(promises).then(function () { });
  93613. };
  93614. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  93615. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  93616. animation._babylonAnimationGroup = babylonAnimationGroup;
  93617. var promises = new Array();
  93618. GLTF2.ArrayItem.Assign(animation.channels);
  93619. GLTF2.ArrayItem.Assign(animation.samplers);
  93620. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  93621. var channel = _a[_i];
  93622. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  93623. }
  93624. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  93625. return Promise.all(promises).then(function () {
  93626. babylonAnimationGroup.normalize();
  93627. });
  93628. };
  93629. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  93630. var _this = this;
  93631. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  93632. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  93633. return Promise.resolve();
  93634. }
  93635. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  93636. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  93637. var targetPath;
  93638. var animationType;
  93639. switch (channel.target.path) {
  93640. case "translation" /* TRANSLATION */: {
  93641. targetPath = "position";
  93642. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  93643. break;
  93644. }
  93645. case "rotation" /* ROTATION */: {
  93646. targetPath = "rotationQuaternion";
  93647. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  93648. break;
  93649. }
  93650. case "scale" /* SCALE */: {
  93651. targetPath = "scaling";
  93652. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  93653. break;
  93654. }
  93655. case "weights" /* WEIGHTS */: {
  93656. targetPath = "influence";
  93657. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  93658. break;
  93659. }
  93660. default: {
  93661. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  93662. }
  93663. }
  93664. var outputBufferOffset = 0;
  93665. var getNextOutputValue;
  93666. switch (targetPath) {
  93667. case "position": {
  93668. getNextOutputValue = function () {
  93669. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  93670. outputBufferOffset += 3;
  93671. return value;
  93672. };
  93673. break;
  93674. }
  93675. case "rotationQuaternion": {
  93676. getNextOutputValue = function () {
  93677. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  93678. outputBufferOffset += 4;
  93679. return value;
  93680. };
  93681. break;
  93682. }
  93683. case "scaling": {
  93684. getNextOutputValue = function () {
  93685. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  93686. outputBufferOffset += 3;
  93687. return value;
  93688. };
  93689. break;
  93690. }
  93691. case "influence": {
  93692. getNextOutputValue = function () {
  93693. var value = new Array(targetNode._numMorphTargets);
  93694. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  93695. value[i] = data.output[outputBufferOffset++];
  93696. }
  93697. return value;
  93698. };
  93699. break;
  93700. }
  93701. }
  93702. var getNextKey;
  93703. switch (data.interpolation) {
  93704. case "STEP" /* STEP */: {
  93705. getNextKey = function (frameIndex) { return ({
  93706. frame: data.input[frameIndex],
  93707. value: getNextOutputValue(),
  93708. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  93709. }); };
  93710. break;
  93711. }
  93712. case "LINEAR" /* LINEAR */: {
  93713. getNextKey = function (frameIndex) { return ({
  93714. frame: data.input[frameIndex],
  93715. value: getNextOutputValue()
  93716. }); };
  93717. break;
  93718. }
  93719. case "CUBICSPLINE" /* CUBICSPLINE */: {
  93720. getNextKey = function (frameIndex) { return ({
  93721. frame: data.input[frameIndex],
  93722. inTangent: getNextOutputValue(),
  93723. value: getNextOutputValue(),
  93724. outTangent: getNextOutputValue()
  93725. }); };
  93726. break;
  93727. }
  93728. }
  93729. var keys;
  93730. if (data.input.length === 1) {
  93731. var key = getNextKey(0);
  93732. keys = [
  93733. { frame: key.frame, value: key.value },
  93734. { frame: key.frame + 1, value: key.value }
  93735. ];
  93736. }
  93737. else {
  93738. keys = new Array(data.input.length);
  93739. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  93740. keys[frameIndex] = getNextKey(frameIndex);
  93741. }
  93742. }
  93743. if (targetPath === "influence") {
  93744. var _loop_1 = function (targetIndex) {
  93745. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  93746. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  93747. babylonAnimation.setKeys(keys.map(function (key) { return ({
  93748. frame: key.frame,
  93749. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  93750. value: key.value[targetIndex],
  93751. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  93752. }); }));
  93753. _this._forEachNodeMesh(targetNode, function (babylonMesh) {
  93754. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  93755. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  93756. });
  93757. };
  93758. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  93759. _loop_1(targetIndex);
  93760. }
  93761. }
  93762. else {
  93763. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  93764. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  93765. babylonAnimation.setKeys(keys);
  93766. if (targetNode._babylonAnimationTargets) {
  93767. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  93768. var target = _a[_i];
  93769. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  93770. }
  93771. }
  93772. }
  93773. });
  93774. };
  93775. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  93776. if (sampler._data) {
  93777. return sampler._data;
  93778. }
  93779. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  93780. switch (interpolation) {
  93781. case "STEP" /* STEP */:
  93782. case "LINEAR" /* LINEAR */:
  93783. case "CUBICSPLINE" /* CUBICSPLINE */: {
  93784. break;
  93785. }
  93786. default: {
  93787. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  93788. }
  93789. }
  93790. var inputData;
  93791. var outputData;
  93792. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  93793. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  93794. sampler._data = Promise.all([
  93795. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  93796. inputData = data;
  93797. }),
  93798. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  93799. outputData = data;
  93800. })
  93801. ]).then(function () {
  93802. return {
  93803. input: inputData,
  93804. interpolation: interpolation,
  93805. output: outputData,
  93806. };
  93807. });
  93808. return sampler._data;
  93809. };
  93810. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  93811. if (buffer._data) {
  93812. return buffer._data;
  93813. }
  93814. if (!buffer.uri) {
  93815. throw new Error(context + ": Uri is missing");
  93816. }
  93817. buffer._data = this._loadUriAsync(context, buffer.uri);
  93818. return buffer._data;
  93819. };
  93820. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  93821. if (bufferView._data) {
  93822. return bufferView._data;
  93823. }
  93824. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  93825. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  93826. try {
  93827. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  93828. }
  93829. catch (e) {
  93830. throw new Error(context + ": " + e.message);
  93831. }
  93832. });
  93833. return bufferView._data;
  93834. };
  93835. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  93836. var _this = this;
  93837. if (accessor.sparse) {
  93838. throw new Error(context + ": Sparse accessors are not currently supported");
  93839. }
  93840. if (accessor._data) {
  93841. return accessor._data;
  93842. }
  93843. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  93844. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  93845. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  93846. var byteOffset = accessor.byteOffset || 0;
  93847. var byteStride = bufferView.byteStride;
  93848. if (byteStride === 0) {
  93849. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  93850. }
  93851. try {
  93852. switch (accessor.componentType) {
  93853. case 5120 /* BYTE */: {
  93854. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93855. }
  93856. case 5121 /* UNSIGNED_BYTE */: {
  93857. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93858. }
  93859. case 5122 /* SHORT */: {
  93860. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93861. }
  93862. case 5123 /* UNSIGNED_SHORT */: {
  93863. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93864. }
  93865. case 5125 /* UNSIGNED_INT */: {
  93866. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93867. }
  93868. case 5126 /* FLOAT */: {
  93869. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93870. }
  93871. default: {
  93872. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  93873. }
  93874. }
  93875. }
  93876. catch (e) {
  93877. throw new Error(context + ": " + e.messsage);
  93878. }
  93879. });
  93880. return accessor._data;
  93881. };
  93882. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  93883. byteOffset += data.byteOffset;
  93884. var targetLength = count * numComponents;
  93885. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  93886. return new typedArray(data.buffer, byteOffset, targetLength);
  93887. }
  93888. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  93889. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  93890. var targetBuffer = new typedArray(targetLength);
  93891. var sourceIndex = 0;
  93892. var targetIndex = 0;
  93893. while (targetIndex < targetLength) {
  93894. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  93895. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  93896. targetIndex++;
  93897. }
  93898. sourceIndex += elementStride;
  93899. }
  93900. return targetBuffer;
  93901. };
  93902. GLTFLoader.prototype._getDefaultMaterial = function () {
  93903. var id = "__gltf_default";
  93904. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  93905. if (!babylonMaterial) {
  93906. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  93907. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  93908. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93909. babylonMaterial.metallic = 1;
  93910. babylonMaterial.roughness = 1;
  93911. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93912. }
  93913. return babylonMaterial;
  93914. };
  93915. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  93916. var promises = new Array();
  93917. var babylonMaterial = material._babylonMaterial;
  93918. // Ensure metallic workflow
  93919. babylonMaterial.metallic = 1;
  93920. babylonMaterial.roughness = 1;
  93921. var properties = material.pbrMetallicRoughness;
  93922. if (properties) {
  93923. if (properties.baseColorFactor) {
  93924. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  93925. babylonMaterial.alpha = properties.baseColorFactor[3];
  93926. }
  93927. else {
  93928. babylonMaterial.albedoColor = BABYLON.Color3.White();
  93929. }
  93930. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  93931. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  93932. if (properties.baseColorTexture) {
  93933. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  93934. babylonMaterial.albedoTexture = texture;
  93935. }));
  93936. }
  93937. if (properties.metallicRoughnessTexture) {
  93938. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  93939. babylonMaterial.metallicTexture = texture;
  93940. }));
  93941. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  93942. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  93943. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  93944. }
  93945. }
  93946. this._loadMaterialAlphaProperties(context, material);
  93947. return Promise.all(promises).then(function () { });
  93948. };
  93949. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  93950. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, assign);
  93951. if (promise) {
  93952. return promise;
  93953. }
  93954. material._babylonMeshes = material._babylonMeshes || [];
  93955. material._babylonMeshes.push(babylonMesh);
  93956. if (!material._loaded) {
  93957. var promises = new Array();
  93958. var babylonMaterial = this._createMaterial(material);
  93959. material._babylonMaterial = babylonMaterial;
  93960. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  93961. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  93962. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93963. material._loaded = Promise.all(promises).then(function () { });
  93964. }
  93965. assign(material._babylonMaterial);
  93966. return material._loaded;
  93967. };
  93968. GLTFLoader.prototype._createMaterial = function (material) {
  93969. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  93970. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93971. return babylonMaterial;
  93972. };
  93973. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  93974. var promises = new Array();
  93975. var babylonMaterial = material._babylonMaterial;
  93976. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  93977. if (material.doubleSided) {
  93978. babylonMaterial.backFaceCulling = false;
  93979. babylonMaterial.twoSidedLighting = true;
  93980. }
  93981. if (material.normalTexture) {
  93982. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  93983. babylonMaterial.bumpTexture = texture;
  93984. }));
  93985. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  93986. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  93987. if (material.normalTexture.scale != undefined) {
  93988. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  93989. }
  93990. }
  93991. if (material.occlusionTexture) {
  93992. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  93993. babylonMaterial.ambientTexture = texture;
  93994. }));
  93995. babylonMaterial.useAmbientInGrayScale = true;
  93996. if (material.occlusionTexture.strength != undefined) {
  93997. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  93998. }
  93999. }
  94000. if (material.emissiveTexture) {
  94001. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  94002. babylonMaterial.emissiveTexture = texture;
  94003. }));
  94004. }
  94005. return Promise.all(promises).then(function () { });
  94006. };
  94007. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  94008. var babylonMaterial = material._babylonMaterial;
  94009. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  94010. switch (alphaMode) {
  94011. case "OPAQUE" /* OPAQUE */: {
  94012. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  94013. break;
  94014. }
  94015. case "MASK" /* MASK */: {
  94016. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  94017. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  94018. if (babylonMaterial.alpha) {
  94019. if (babylonMaterial.alpha === 0) {
  94020. babylonMaterial.alphaCutOff = 1;
  94021. }
  94022. else {
  94023. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  94024. }
  94025. babylonMaterial.alpha = 1;
  94026. }
  94027. if (babylonMaterial.albedoTexture) {
  94028. babylonMaterial.albedoTexture.hasAlpha = true;
  94029. }
  94030. break;
  94031. }
  94032. case "BLEND" /* BLEND */: {
  94033. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  94034. if (babylonMaterial.albedoTexture) {
  94035. babylonMaterial.albedoTexture.hasAlpha = true;
  94036. babylonMaterial.useAlphaFromAlbedoTexture = true;
  94037. }
  94038. break;
  94039. }
  94040. default: {
  94041. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  94042. }
  94043. }
  94044. };
  94045. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  94046. var _this = this;
  94047. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  94048. context = "#/textures/" + textureInfo.index;
  94049. var promises = new Array();
  94050. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  94051. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  94052. var deferred = new BABYLON.Deferred();
  94053. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  94054. if (!_this._disposed) {
  94055. deferred.resolve();
  94056. }
  94057. }, function (message, exception) {
  94058. if (!_this._disposed) {
  94059. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  94060. }
  94061. });
  94062. promises.push(deferred.promise);
  94063. babylonTexture.name = texture.name || "texture" + texture._index;
  94064. babylonTexture.wrapU = samplerData.wrapU;
  94065. babylonTexture.wrapV = samplerData.wrapV;
  94066. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  94067. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  94068. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  94069. babylonTexture.updateURL(objectURL);
  94070. }));
  94071. assign(babylonTexture);
  94072. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  94073. return Promise.all(promises).then(function () { });
  94074. };
  94075. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  94076. if (!sampler._data) {
  94077. sampler._data = {
  94078. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  94079. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  94080. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  94081. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  94082. };
  94083. }
  94084. ;
  94085. return sampler._data;
  94086. };
  94087. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  94088. if (image._objectURL) {
  94089. return image._objectURL;
  94090. }
  94091. var promise;
  94092. if (image.uri) {
  94093. promise = this._loadUriAsync(context, image.uri);
  94094. }
  94095. else {
  94096. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  94097. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  94098. }
  94099. image._objectURL = promise.then(function (data) {
  94100. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  94101. });
  94102. return image._objectURL;
  94103. };
  94104. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  94105. var _this = this;
  94106. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  94107. if (promise) {
  94108. return promise;
  94109. }
  94110. if (!GLTFLoader._ValidateUri(uri)) {
  94111. throw new Error(context + ": Uri '" + uri + "' is invalid");
  94112. }
  94113. if (BABYLON.Tools.IsBase64(uri)) {
  94114. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  94115. }
  94116. return new Promise(function (resolve, reject) {
  94117. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  94118. if (!_this._disposed) {
  94119. resolve(new Uint8Array(data));
  94120. }
  94121. }, function (event) {
  94122. if (!_this._disposed) {
  94123. try {
  94124. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  94125. request._lengthComputable = event.lengthComputable;
  94126. request._loaded = event.loaded;
  94127. request._total = event.total;
  94128. _this._onProgress();
  94129. }
  94130. }
  94131. catch (e) {
  94132. reject(e);
  94133. }
  94134. }
  94135. }, _this._babylonScene.database, true, function (request, exception) {
  94136. if (!_this._disposed) {
  94137. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  94138. }
  94139. });
  94140. _this._requests.push(request);
  94141. });
  94142. };
  94143. GLTFLoader.prototype._onProgress = function () {
  94144. if (!this._progressCallback) {
  94145. return;
  94146. }
  94147. var lengthComputable = true;
  94148. var loaded = 0;
  94149. var total = 0;
  94150. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  94151. var request = _a[_i];
  94152. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  94153. return;
  94154. }
  94155. lengthComputable = lengthComputable && request._lengthComputable;
  94156. loaded += request._loaded;
  94157. total += request._total;
  94158. }
  94159. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  94160. };
  94161. GLTFLoader._GetProperty = function (context, array, index) {
  94162. if (!array || index == undefined || !array[index]) {
  94163. throw new Error(context + ": Failed to find index (" + index + ")");
  94164. }
  94165. return array[index];
  94166. };
  94167. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  94168. // Set defaults if undefined
  94169. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  94170. switch (mode) {
  94171. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  94172. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  94173. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  94174. default:
  94175. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  94176. return BABYLON.Texture.WRAP_ADDRESSMODE;
  94177. }
  94178. };
  94179. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  94180. // Set defaults if undefined
  94181. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  94182. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  94183. if (magFilter === 9729 /* LINEAR */) {
  94184. switch (minFilter) {
  94185. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  94186. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  94187. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  94188. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  94189. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  94190. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  94191. default:
  94192. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  94193. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  94194. }
  94195. }
  94196. else {
  94197. if (magFilter !== 9728 /* NEAREST */) {
  94198. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  94199. }
  94200. switch (minFilter) {
  94201. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  94202. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  94203. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  94204. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  94205. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  94206. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  94207. default:
  94208. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  94209. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  94210. }
  94211. }
  94212. };
  94213. GLTFLoader._GetNumComponents = function (context, type) {
  94214. switch (type) {
  94215. case "SCALAR": return 1;
  94216. case "VEC2": return 2;
  94217. case "VEC3": return 3;
  94218. case "VEC4": return 4;
  94219. case "MAT2": return 4;
  94220. case "MAT3": return 9;
  94221. case "MAT4": return 16;
  94222. }
  94223. throw new Error(context + ": Invalid type (" + type + ")");
  94224. };
  94225. GLTFLoader._ValidateUri = function (uri) {
  94226. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  94227. };
  94228. GLTFLoader.prototype._compileMaterialsAsync = function () {
  94229. var promises = new Array();
  94230. if (this._gltf.materials) {
  94231. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  94232. var material = _a[_i];
  94233. var babylonMaterial = material._babylonMaterial;
  94234. var babylonMeshes = material._babylonMeshes;
  94235. if (babylonMaterial && babylonMeshes) {
  94236. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  94237. var babylonMesh = babylonMeshes_1[_b];
  94238. // Ensure nonUniformScaling is set if necessary.
  94239. babylonMesh.computeWorldMatrix(true);
  94240. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  94241. if (this.useClipPlane) {
  94242. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  94243. }
  94244. }
  94245. }
  94246. }
  94247. }
  94248. return Promise.all(promises).then(function () { });
  94249. };
  94250. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  94251. var promises = new Array();
  94252. var lights = this._babylonScene.lights;
  94253. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  94254. var light = lights_1[_i];
  94255. var generator = light.getShadowGenerator();
  94256. if (generator) {
  94257. promises.push(generator.forceCompilationAsync());
  94258. }
  94259. }
  94260. return Promise.all(promises).then(function () { });
  94261. };
  94262. GLTFLoader.prototype._clear = function () {
  94263. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  94264. var request = _a[_i];
  94265. request.abort();
  94266. }
  94267. this._requests.length = 0;
  94268. if (this._gltf && this._gltf.images) {
  94269. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  94270. var image = _c[_b];
  94271. if (image._objectURL) {
  94272. image._objectURL.then(function (value) {
  94273. URL.revokeObjectURL(value);
  94274. });
  94275. image._objectURL = undefined;
  94276. }
  94277. }
  94278. }
  94279. delete this._gltf;
  94280. delete this._babylonScene;
  94281. this._completePromises.length = 0;
  94282. for (var name_3 in this._extensions) {
  94283. this._extensions[name_3].dispose();
  94284. }
  94285. this._extensions = {};
  94286. delete this._rootBabylonMesh;
  94287. delete this._progressCallback;
  94288. this.onMeshLoadedObservable.clear();
  94289. this.onTextureLoadedObservable.clear();
  94290. this.onMaterialLoadedObservable.clear();
  94291. };
  94292. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  94293. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  94294. var name_4 = _a[_i];
  94295. var extension = this._extensions[name_4];
  94296. if (extension.enabled) {
  94297. var promise = actionAsync(extension);
  94298. if (promise) {
  94299. return promise;
  94300. }
  94301. }
  94302. }
  94303. return null;
  94304. };
  94305. GLTFLoader._Names = new Array();
  94306. GLTFLoader._Factories = {};
  94307. return GLTFLoader;
  94308. }());
  94309. GLTF2.GLTFLoader = GLTFLoader;
  94310. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  94311. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94312. })(BABYLON || (BABYLON = {}));
  94313. //# sourceMappingURL=babylon.glTFLoader.js.map
  94314. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  94315. var BABYLON;
  94316. (function (BABYLON) {
  94317. var GLTF2;
  94318. (function (GLTF2) {
  94319. var GLTFLoaderExtension = /** @class */ (function () {
  94320. function GLTFLoaderExtension(loader) {
  94321. this.enabled = true;
  94322. this._loader = loader;
  94323. }
  94324. GLTFLoaderExtension.prototype.dispose = function () {
  94325. delete this._loader;
  94326. };
  94327. // #region Overridable Methods
  94328. /** Override this method to modify the default behavior for loading scenes. */
  94329. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  94330. /** Override this method to modify the default behavior for loading nodes. */
  94331. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  94332. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  94333. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  94334. /** Override this method to modify the default behavior for loading materials. */
  94335. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) { return null; };
  94336. /** Override this method to modify the default behavior for loading uris. */
  94337. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  94338. // #endregion
  94339. /** Helper method called by a loader extension to load an glTF extension. */
  94340. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  94341. if (!property.extensions) {
  94342. return null;
  94343. }
  94344. var extensions = property.extensions;
  94345. var extension = extensions[this.name];
  94346. if (!extension) {
  94347. return null;
  94348. }
  94349. // Clear out the extension before executing the action to avoid recursing into the same property.
  94350. delete extensions[this.name];
  94351. try {
  94352. return actionAsync(context + "/extensions/" + this.name, extension);
  94353. }
  94354. finally {
  94355. // Restore the extension after executing the action.
  94356. extensions[this.name] = extension;
  94357. }
  94358. };
  94359. /** Helper method called by the loader to allow extensions to override loading scenes. */
  94360. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  94361. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  94362. };
  94363. /** Helper method called by the loader to allow extensions to override loading nodes. */
  94364. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  94365. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  94366. };
  94367. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  94368. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  94369. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  94370. };
  94371. /** Helper method called by the loader to allow extensions to override loading materials. */
  94372. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, assign) {
  94373. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, assign); });
  94374. };
  94375. /** Helper method called by the loader to allow extensions to override loading uris. */
  94376. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  94377. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  94378. };
  94379. return GLTFLoaderExtension;
  94380. }());
  94381. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  94382. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94383. })(BABYLON || (BABYLON = {}));
  94384. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  94385. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94386. var BABYLON;
  94387. (function (BABYLON) {
  94388. var GLTF2;
  94389. (function (GLTF2) {
  94390. var Extensions;
  94391. (function (Extensions) {
  94392. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  94393. var NAME = "MSFT_lod";
  94394. var MSFT_lod = /** @class */ (function (_super) {
  94395. __extends(MSFT_lod, _super);
  94396. function MSFT_lod() {
  94397. var _this = _super !== null && _super.apply(this, arguments) || this;
  94398. _this.name = NAME;
  94399. /**
  94400. * Maximum number of LODs to load, starting from the lowest LOD.
  94401. */
  94402. _this.maxLODsToLoad = Number.MAX_VALUE;
  94403. _this._loadingNodeLOD = null;
  94404. _this._loadNodeSignals = {};
  94405. _this._loadingMaterialLOD = null;
  94406. _this._loadMaterialSignals = {};
  94407. return _this;
  94408. }
  94409. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  94410. var _this = this;
  94411. return this._loadExtensionAsync(context, node, function (context, extension) {
  94412. var firstPromise;
  94413. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  94414. var _loop_1 = function (indexLOD) {
  94415. var nodeLOD = nodeLODs[indexLOD];
  94416. if (indexLOD !== 0) {
  94417. _this._loadingNodeLOD = nodeLOD;
  94418. if (!_this._loadNodeSignals[nodeLOD._index]) {
  94419. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  94420. }
  94421. }
  94422. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  94423. if (indexLOD !== 0) {
  94424. var previousNodeLOD = nodeLODs[indexLOD - 1];
  94425. if (previousNodeLOD._babylonMesh) {
  94426. previousNodeLOD._babylonMesh.dispose();
  94427. delete previousNodeLOD._babylonMesh;
  94428. }
  94429. }
  94430. if (indexLOD !== nodeLODs.length - 1) {
  94431. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  94432. if (_this._loadNodeSignals[nodeIndex]) {
  94433. _this._loadNodeSignals[nodeIndex].resolve();
  94434. delete _this._loadNodeSignals[nodeIndex];
  94435. }
  94436. }
  94437. });
  94438. if (indexLOD === 0) {
  94439. firstPromise = promise;
  94440. }
  94441. else {
  94442. _this._loader._completePromises.push(promise);
  94443. _this._loadingNodeLOD = null;
  94444. }
  94445. };
  94446. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  94447. _loop_1(indexLOD);
  94448. }
  94449. return firstPromise;
  94450. });
  94451. };
  94452. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  94453. var _this = this;
  94454. // Don't load material LODs if already loading a node LOD.
  94455. if (this._loadingNodeLOD) {
  94456. return null;
  94457. }
  94458. return this._loadExtensionAsync(context, material, function (context, extension) {
  94459. var firstPromise;
  94460. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  94461. var _loop_2 = function (indexLOD) {
  94462. var materialLOD = materialLODs[indexLOD];
  94463. if (indexLOD !== 0) {
  94464. _this._loadingMaterialLOD = materialLOD;
  94465. if (!_this._loadMaterialSignals[materialLOD._index]) {
  94466. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  94467. }
  94468. }
  94469. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, indexLOD === 0 ? assign : function () { }).then(function () {
  94470. if (indexLOD !== 0) {
  94471. assign(materialLOD._babylonMaterial);
  94472. var previousMaterialLOD = materialLODs[indexLOD - 1];
  94473. if (previousMaterialLOD._babylonMaterial) {
  94474. previousMaterialLOD._babylonMaterial.dispose();
  94475. delete previousMaterialLOD._babylonMaterial;
  94476. }
  94477. }
  94478. if (indexLOD !== materialLODs.length - 1) {
  94479. var materialIndex = materialLODs[indexLOD + 1]._index;
  94480. if (_this._loadMaterialSignals[materialIndex]) {
  94481. _this._loadMaterialSignals[materialIndex].resolve();
  94482. delete _this._loadMaterialSignals[materialIndex];
  94483. }
  94484. }
  94485. });
  94486. if (indexLOD === 0) {
  94487. firstPromise = promise;
  94488. }
  94489. else {
  94490. _this._loader._completePromises.push(promise);
  94491. _this._loadingMaterialLOD = null;
  94492. }
  94493. };
  94494. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  94495. _loop_2(indexLOD);
  94496. }
  94497. return firstPromise;
  94498. });
  94499. };
  94500. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  94501. var _this = this;
  94502. // Defer the loading of uris if loading a material or node LOD.
  94503. if (this._loadingMaterialLOD) {
  94504. var index = this._loadingMaterialLOD._index;
  94505. return this._loadMaterialSignals[index].promise.then(function () {
  94506. return _this._loader._loadUriAsync(context, uri);
  94507. });
  94508. }
  94509. else if (this._loadingNodeLOD) {
  94510. var index = this._loadingNodeLOD._index;
  94511. return this._loadNodeSignals[index].promise.then(function () {
  94512. return _this._loader._loadUriAsync(context, uri);
  94513. });
  94514. }
  94515. return null;
  94516. };
  94517. /**
  94518. * Gets an array of LOD properties from lowest to highest.
  94519. */
  94520. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  94521. if (this.maxLODsToLoad <= 0) {
  94522. throw new Error("maxLODsToLoad must be greater than zero");
  94523. }
  94524. var properties = new Array();
  94525. for (var i = ids.length - 1; i >= 0; i--) {
  94526. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  94527. if (properties.length === this.maxLODsToLoad) {
  94528. return properties;
  94529. }
  94530. }
  94531. properties.push(property);
  94532. return properties;
  94533. };
  94534. return MSFT_lod;
  94535. }(GLTF2.GLTFLoaderExtension));
  94536. Extensions.MSFT_lod = MSFT_lod;
  94537. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  94538. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94539. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94540. })(BABYLON || (BABYLON = {}));
  94541. //# sourceMappingURL=MSFT_lod.js.map
  94542. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94543. var BABYLON;
  94544. (function (BABYLON) {
  94545. var GLTF2;
  94546. (function (GLTF2) {
  94547. var Extensions;
  94548. (function (Extensions) {
  94549. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  94550. var NAME = "KHR_draco_mesh_compression";
  94551. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  94552. __extends(KHR_draco_mesh_compression, _super);
  94553. function KHR_draco_mesh_compression(loader) {
  94554. var _this = _super.call(this, loader) || this;
  94555. _this.name = NAME;
  94556. _this._dracoCompression = null;
  94557. // Disable extension if decoder is not available.
  94558. if (!BABYLON.DracoCompression.DecoderUrl) {
  94559. _this.enabled = false;
  94560. }
  94561. return _this;
  94562. }
  94563. KHR_draco_mesh_compression.prototype.dispose = function () {
  94564. if (this._dracoCompression) {
  94565. this._dracoCompression.dispose();
  94566. }
  94567. _super.prototype.dispose.call(this);
  94568. };
  94569. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  94570. var _this = this;
  94571. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  94572. if (primitive.mode != undefined) {
  94573. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  94574. primitive.mode !== 4 /* TRIANGLES */) {
  94575. throw new Error(context + ": Unsupported mode " + primitive.mode);
  94576. }
  94577. // TODO: handle triangle strips
  94578. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  94579. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  94580. }
  94581. }
  94582. var attributes = {};
  94583. var loadAttribute = function (name, kind) {
  94584. var uniqueId = extension.attributes[name];
  94585. if (uniqueId == undefined) {
  94586. return;
  94587. }
  94588. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  94589. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  94590. babylonMesh._delayInfo.push(kind);
  94591. }
  94592. attributes[kind] = uniqueId;
  94593. };
  94594. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  94595. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  94596. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  94597. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  94598. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  94599. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  94600. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  94601. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  94602. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  94603. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  94604. try {
  94605. if (!_this._dracoCompression) {
  94606. _this._dracoCompression = new BABYLON.DracoCompression();
  94607. }
  94608. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  94609. }
  94610. catch (e) {
  94611. throw new Error(context + ": " + e.message);
  94612. }
  94613. });
  94614. });
  94615. };
  94616. return KHR_draco_mesh_compression;
  94617. }(GLTF2.GLTFLoaderExtension));
  94618. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  94619. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  94620. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94621. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94622. })(BABYLON || (BABYLON = {}));
  94623. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  94624. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94625. var BABYLON;
  94626. (function (BABYLON) {
  94627. var GLTF2;
  94628. (function (GLTF2) {
  94629. var Extensions;
  94630. (function (Extensions) {
  94631. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  94632. var NAME = "KHR_materials_pbrSpecularGlossiness";
  94633. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  94634. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  94635. function KHR_materials_pbrSpecularGlossiness() {
  94636. var _this = _super !== null && _super.apply(this, arguments) || this;
  94637. _this.name = NAME;
  94638. return _this;
  94639. }
  94640. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  94641. var _this = this;
  94642. return this._loadExtensionAsync(context, material, function (context, extension) {
  94643. material._babylonMeshes = material._babylonMeshes || [];
  94644. material._babylonMeshes.push(babylonMesh);
  94645. if (!material._loaded) {
  94646. var promises = new Array();
  94647. var babylonMaterial = _this._loader._createMaterial(material);
  94648. material._babylonMaterial = babylonMaterial;
  94649. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  94650. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension));
  94651. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  94652. material._loaded = Promise.all(promises).then(function () { });
  94653. }
  94654. assign(material._babylonMaterial);
  94655. return material._loaded;
  94656. });
  94657. };
  94658. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties) {
  94659. var promises = new Array();
  94660. var babylonMaterial = material._babylonMaterial;
  94661. if (properties.diffuseFactor) {
  94662. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  94663. babylonMaterial.alpha = properties.diffuseFactor[3];
  94664. }
  94665. else {
  94666. babylonMaterial.albedoColor = BABYLON.Color3.White();
  94667. }
  94668. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  94669. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  94670. if (properties.diffuseTexture) {
  94671. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  94672. babylonMaterial.albedoTexture = texture;
  94673. }));
  94674. }
  94675. if (properties.specularGlossinessTexture) {
  94676. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  94677. babylonMaterial.reflectivityTexture = texture;
  94678. }));
  94679. babylonMaterial.reflectivityTexture.hasAlpha = true;
  94680. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  94681. }
  94682. this._loader._loadMaterialAlphaProperties(context, material);
  94683. return Promise.all(promises).then(function () { });
  94684. };
  94685. return KHR_materials_pbrSpecularGlossiness;
  94686. }(GLTF2.GLTFLoaderExtension));
  94687. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  94688. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  94689. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94690. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94691. })(BABYLON || (BABYLON = {}));
  94692. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  94693. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94694. var BABYLON;
  94695. (function (BABYLON) {
  94696. var GLTF2;
  94697. (function (GLTF2) {
  94698. var Extensions;
  94699. (function (Extensions) {
  94700. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  94701. var NAME = "KHR_lights";
  94702. var LightType;
  94703. (function (LightType) {
  94704. LightType["AMBIENT"] = "ambient";
  94705. LightType["DIRECTIONAL"] = "directional";
  94706. LightType["POINT"] = "point";
  94707. LightType["SPOT"] = "spot";
  94708. })(LightType || (LightType = {}));
  94709. var KHR_lights = /** @class */ (function (_super) {
  94710. __extends(KHR_lights, _super);
  94711. function KHR_lights() {
  94712. var _this = _super !== null && _super.apply(this, arguments) || this;
  94713. _this.name = NAME;
  94714. return _this;
  94715. }
  94716. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  94717. var _this = this;
  94718. return this._loadExtensionAsync(context, scene, function (context, extension) {
  94719. var promise = _this._loader._loadSceneAsync(context, scene);
  94720. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  94721. if (light.type !== LightType.AMBIENT) {
  94722. throw new Error(context + ": Only ambient lights are allowed on a scene");
  94723. }
  94724. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  94725. return promise;
  94726. });
  94727. };
  94728. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  94729. var _this = this;
  94730. return this._loadExtensionAsync(context, node, function (context, extension) {
  94731. var promise = _this._loader._loadNodeAsync(context, node);
  94732. var babylonLight;
  94733. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  94734. var name = node._babylonMesh.name;
  94735. switch (light.type) {
  94736. case LightType.AMBIENT: {
  94737. throw new Error(context + ": Ambient lights are not allowed on a node");
  94738. }
  94739. case LightType.DIRECTIONAL: {
  94740. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  94741. break;
  94742. }
  94743. case LightType.POINT: {
  94744. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  94745. break;
  94746. }
  94747. case LightType.SPOT: {
  94748. var spotLight = light;
  94749. // TODO: support inner and outer cone angles
  94750. //const innerConeAngle = spotLight.innerConeAngle || 0;
  94751. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  94752. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  94753. break;
  94754. }
  94755. default: {
  94756. throw new Error(context + ": Invalid light type (" + light.type + ")");
  94757. }
  94758. }
  94759. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  94760. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  94761. babylonLight.parent = node._babylonMesh;
  94762. return promise;
  94763. });
  94764. };
  94765. Object.defineProperty(KHR_lights.prototype, "_lights", {
  94766. get: function () {
  94767. var extensions = this._loader._gltf.extensions;
  94768. if (!extensions || !extensions[this.name]) {
  94769. throw new Error("#/extensions: '" + this.name + "' not found");
  94770. }
  94771. var extension = extensions[this.name];
  94772. return extension.lights;
  94773. },
  94774. enumerable: true,
  94775. configurable: true
  94776. });
  94777. return KHR_lights;
  94778. }(GLTF2.GLTFLoaderExtension));
  94779. Extensions.KHR_lights = KHR_lights;
  94780. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  94781. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94782. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94783. })(BABYLON || (BABYLON = {}));
  94784. //# sourceMappingURL=KHR_lights.js.map
  94785. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  94786. globalObject["BABYLON"] = BABYLON;
  94787. 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 WorkerPool = BABYLON.WorkerPool;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var DepthTextureCreationOptions = BABYLON.DepthTextureCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationPropertiesOverride = BABYLON.AnimationPropertiesOverride;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var DracoCompression = BABYLON.DracoCompression;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var DaydreamController = BABYLON.DaydreamController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var ChromaticAberrationPostProcess = BABYLON.ChromaticAberrationPostProcess;var SharpenPostProcess = BABYLON.SharpenPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;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 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;var Space = BABYLON.Space ;var Orientation = BABYLON.Orientation ;var AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation ;var WorkerTaskType = BABYLON.WorkerTaskType ;var WorkerReplyType = BABYLON.WorkerReplyType ;var Xbox360Button = BABYLON.Xbox360Button ;var Xbox360Dpad = BABYLON.Xbox360Dpad ;var PoseEnabledControllerType = BABYLON.PoseEnabledControllerType ;var DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel ;var TonemappingOperator = BABYLON.TonemappingOperator ;var PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff ;var PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode ;var JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;var GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode ;var GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode ;var GLTFLoaderState = BABYLON.GLTFLoaderState ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;
  94788. 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,WorkerPool,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,DepthTextureCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationPropertiesOverride,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,DracoCompression,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,DaydreamController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,ChromaticAberrationPostProcess,SharpenPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,DepthOfFieldMergePostProcess,CircleOfConfusionPostProcess,DepthOfFieldEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,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,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,JoystickAxis ,SimplificationType ,AssetTaskState ,GLTFLoaderCoordinateSystemMode ,GLTFLoaderAnimationStartMode ,GLTFLoaderState ,GLTF1 ,GLTF1 ,GLTF1 ,GLTF1 ,GLTF1 ,GLTF1 ,GLTF2 ,GLTF2 ,GLTF2 ,GLTF2 ,GLTF2 ,GLTF2 ,GLTF2 };